Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upsert multiple rows in PostgreSQL

Tags:

I'm trying to write a query like this in PostgreSQL 9.5.2:

INSERT INTO a (id, x)     SELECT id, x FROM b ON CONFLICT (id) DO UPDATE     SET x = b.x     WHERE b.y < 100 

but I get ERROR: missing FROM-clause entry for table "b". I must be missing something basic, but how do I refer to the row being inserted in the UPDATE clause? Or is there some other way?

like image 268
usethe4ce Avatar asked Apr 29 '16 06:04

usethe4ce


People also ask

How does upsert work in PostgreSQL?

In relational databases, the term upsert is referred to as merge. The idea is that when you insert a new row into the table, PostgreSQL will update the row if it already exists, otherwise, it will insert the new row. That is why we call the action is upsert (the combination of update or insert).

Does Postgres support upsert?

PostgreSQL lets you either add or modify a record within a table depending on whether the record already exists. This is commonly known as an "upsert" operation (a portmanteau of "insert" and "update").

How do I add multiple rows in PostgreSQL?

PostgreSQL INSERT Multiple Rows First, specify the name of the table that you want to insert data after the INSERT INTO keywords. Second, list the required columns or all columns of the table in parentheses that follow the table name. Third, supply a comma-separated list of rows after the VALUES keyword.

How do I create a multiple update query in PostgreSQL?

It is very easy to update multiple columns in PostgreSQL. Here is the syntax to update multiple columns in PostgreSQL. UPDATE table_name SET column1 = value1, column2 = value2, ... [WHERE condition];


1 Answers

The conflicting values are available through the excluded alias:

INSERT INTO a (id, x) SELECT id, x  FROM b ON CONFLICT (id) DO UPDATE     SET x = excluded.x; 
like image 147
a_horse_with_no_name Avatar answered Nov 03 '22 18:11

a_horse_with_no_name