PostgreSQL – UPDATE with Different WHERE Clauses

postgresqlupdate

I've written a long Query for updating a table, with some large WITH selects. I want to update some columns during some condition and other if other conditions. I tried to write an easy example

WITH sub_select(SELECT column1, column2, column3 FROM my_large_table)
UPDATE my_second_table
SET first_col = column1
WHERE column3 > 1
SET second_col = column2
WHERE column3 = 1
FROM sub_selection;

What I can do is write it as two separate queries, but I prefer to solve it with one query, any suggestions?

with sub_select(SELECT column1, column2, column3 FROM my large_table)
UPDATE my_second_table
SET first_col = column1
WHERE column3 > 1
FROM sub_selection;
with sub_select(SELECT column1, column2, column3 FROM my large_table)
UPDATE my_second_table
SET second_col = column2
WHERE column3 = 1
FROM sub_selection;

Best Answer

It would be helpful if you gave tables and columns, but something like this might work. Basically, move the WHERE into a case statement and set the column equal to itself if the condition is not met.

WITH sub_select(SELECT column1, column2, column3 FROM my_large_table)
UPDATE my_second_table
SET first_col = case when column3 > 1 then column1 else first_col end
, second_col = case when column 3 = 1 then column2 else second_col end
FROM sub_selection;