My SQL query contains a WHERE
clause looking like this:
WHERE
name1 in ('Emily', 'Jack', 'James', 'Chloe')
OR name2 in ('Emily', 'Jack', 'James', 'Chloe')
Note that the same list appears twice, which is quite unsatisfying (and my real list is actually longer).
What would be a better way to write this query?
You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.
At least if you're running on a SQL Server database, yes it is possible. Hi Priya, You can use all the SQL functions, if you have SQL Server as backend database.
When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.
You can use arrays and overlap operator &&
, e.g.:
with my_table(name1, name2) as (
values ('Emily', 'Bob'), ('Ben', 'Jack'), ('Bob', 'Ben')
)
select *
from my_table
where array[name1, name2] && array['Emily', 'Jack', 'James', 'Chloe'];
name1 | name2
-------+-------
Emily | Bob
Ben | Jack
(2 rows)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With