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.
Construct a select query like,
SELECT city from user where (firstName=x and lastName=y) or (firstName=a and lastName=b) or .....
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?
But the WHERE.. IN clause allows only 1 column.
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.
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.
You can GROUP BY multiple columns, to get the count of each combination.
You could do like this:
SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd'));
The sqlfiddle.
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