Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing a WHERE IN on multiple columns in Postgresql

Tags:

sql

postgresql

I have a table 'answers' with an indexed 'problem_id' integer column, a 'times_chosen' integer column, and an 'option' column that's a varchar. Currently the only values for the 'option' column are 'A', 'B', 'C' and 'D', though those may expand later on. I want to increment by one the 'times_chosen' values of many (50-100) answers, when I know the problem_id and option of each of them.

So I need a query that's something like:

UPDATE answers SET times_chosen = times_chosen + 1 WHERE (problem_id, option) IN ((4509, 'B'), (622, 'C'), (1066, 'D'), (4059, 'A'), (4740, 'A')...) 

Is this possible?

like image 463
PreciousBodilyFluids Avatar asked Jul 13 '11 00:07

PreciousBodilyFluids


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?

Answer. Yes, within a WHERE clause you can compare the values of two columns.

How do I SELECT multiple columns in PostgreSQL?

If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.

How do I SELECT multiple columns based on condition 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.


Video Answer


1 Answers

You can join against a virtual table of sorts:

SELECT * FROM answers JOIN (VALUES (4509, 'B'), (622, 'C'), (1066, 'D'), (4059, 'A'), (4740, 'A'))      AS t (p,o) ON p = problem_id AND o = option 

You can do something similar with UPDATE.

like image 167
Frank Farmer Avatar answered Sep 19 '22 23:09

Frank Farmer