How to upsert multiple rows in PostgreSQL

usethe4ce picture usethe4ce · Apr 29, 2016 · Viewed 8.3k times · Source

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?

Answer

a_horse_with_no_name picture a_horse_with_no_name · Apr 29, 2016

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;