Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use same list twice in WHERE clause?

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?

like image 852
Scarabee Avatar asked Mar 09 '17 11:03

Scarabee


People also ask

Can we use 2 conditions in WHERE clause?

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.

Can WHERE clause have multiple values?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

Can we use with clause twice in SQL?

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.

Can we use two columns in WHERE clause in SQL?

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.


1 Answers

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)
like image 79
klin Avatar answered Oct 02 '22 20:10

klin