Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple rows in same query using PostgreSQL

Tags:

sql

postgresql

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' 
like image 656
newUserNameHere Avatar asked Sep 14 '13 02:09

newUserNameHere


People also ask

How do you update multiple rows in a column?

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.

How do I update all rows?

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.


1 Answers

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

like image 114
Roman Pekar Avatar answered Oct 11 '22 03:10

Roman Pekar