Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL multiple columns in IN clause

Tags:

sql

oracle

If we need to query a table based on some set of values for a given column, we can simply use the IN clause.

But if query need to be performed based on multiple columns, we could not use IN clause(grepped in SO threads.)

From other SO threads, we can circumvent this problem using joins or exists clause etc. But they all work if both main table and search data are in the database.

E.g User table: firstName, lastName, City 

Given a list of (firstname, lastName) tuples, I need to get the cities.

I can think of following solutions.

1

Construct a select query like,

SELECT city from user where (firstName=x and lastName=y) or (firstName=a and lastName=b) or ..... 

2

Upload all firstName, lastName values into a staging table and perform a join between 'user' table and the new staging table.

Are there any options for solving this problem and what is the preferred of solving this problem in general?

like image 237
Htaras Avatar asked Oct 23 '12 09:10

Htaras


People also ask

Can we use multiple columns in WHERE clause?

But the WHERE.. IN clause allows only 1 column.

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.

How do you do multiple columns in SQL?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Can we put multiple columns in count in SQL?

You can GROUP BY multiple columns, to get the count of each combination.


1 Answers

You could do like this:

SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd')); 

The sqlfiddle.

like image 62
xdazz Avatar answered Oct 02 '22 08:10

xdazz