Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional query #147

Closed
giltayar opened this issue Jan 31, 2021 · 3 comments
Closed

Conditional query #147

giltayar opened this issue Jan 31, 2021 · 3 comments

Comments

@giltayar
Copy link

Is there a way to do a conditional query, i.e. have the query be different based on a condition. An example (which I'm pretty sure doesn't work):

await db.query(sql`
SELECT * FROM some_table
${someFilter != null ? sql`WHERE some_field = ${someFilter}` : ''}
`)

My only option now, given that I couldn't find a way to do this, is to have two query statements: one with the "WHERE" and one without.

@DeeLindesay
Copy link

If I've understood the docs correctly I think you could do this with sql.join

await db.query(sql.join(
  [
     sql`SELECT * FROM some_table`,
     someFilter != null ? sql` WHERE some_field = ${someFilter}` : sql``
   ],
   ""
))

@ForbesLindesay
Copy link
Owner

You just need to tag the empty string as a fragment of sql, otherwise it is treated as a parameter:

await db.query(sql`
SELECT * FROM some_table
${someFilter != null ? sql`WHERE some_field = ${someFilter}` : sql``}
`)

Using sql.join also works, you can use whichever approach you prefer.

@giltayar
Copy link
Author

Thanks @ForbesLindesay and @DeeLindesay!

Both of your suggestions work. I prefer Dee's suggestion because it doesn't necessitate a nested template literal. But good to know that I can use both.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants