I'm looking to update multiple rows in PostgreSQL in one statement. Is there a way to do something like the following?
UPDATE table SET column_a = 1 where column_b = '123', column_a = 2 where column_b = '345'
First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.
Syntax: UPDATE table_name SET column_name1 = new_value1, column_name2 = new_value2 ---- WHERE condition; Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data.
You can also use update ... from
syntax and use a mapping table. If you want to update more than one column, it's much more generalizable:
update test as t set column_a = c.column_a from (values ('123', 1), ('345', 2) ) as c(column_b, column_a) where c.column_b = t.column_b;
You can add as many columns as you like:
update test as t set column_a = c.column_a, column_c = c.column_c from (values ('123', 1, '---'), ('345', 2, '+++') ) as c(column_b, column_a, column_c) where c.column_b = t.column_b;
sql fiddle demo
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