TExcelTAD
Home › PostgreSQL › PostgreSQL Upsert & RETURNING

PostgreSQL Upsert & RETURNING

Two PostgreSQL features make data-changing statements much more powerful. INSERT … ON CONFLICT ("upsert") inserts a row or, if it already exists, updates it instead. RETURNING makes INSERT, UPDATE, DELETE and MERGE hand back the rows they changed.

RETURNING

Without RETURNING, you would need a second query to find the id that was just generated. With it, the statement returns it directly:

pgsql · try it yourself
INSERT INTO customers (first_name, last_name, email, city, country, joined)
VALUES ('Pia', 'Lund', 'pia@example.com', 'Oslo', 'Norway', '2025-02-01')
RETURNING id, first_name, joined;
 id | first_name |   joined
----+------------+------------
 16 | Pia        | 2025-02-01
(1 row)

INSERT 0 1

RETURNING can contain any expression, and works with UPDATE and DELETE too:

pgsql · try it yourself
UPDATE books
SET price = price + 1
WHERE category_id = 3
RETURNING title, price - 1 AS old_price, price AS new_price;

DELETE FROM orders WHERE status = 'cancelled' RETURNING id, customer_id;
       title        | old_price | new_price
--------------------+-----------+-----------
 Murder at Low Tide |     11.99 |     12.99
 The Quiet Witness  |     13.49 |     14.49
 The Map Thief      |     12.99 |     13.99
(3 rows)

UPDATE 3
 id | customer_id
----+-------------
  5 |           4
 20 |          10
(2 rows)

DELETE 2

In PostgreSQL 18 you can even ask for the old and new version of a row explicitly:

pgsql · try it yourself
UPDATE books SET stock = stock + 5 WHERE id IN (2, 12)
RETURNING title, old.stock AS before, new.stock AS after;
       title       | before | after
-------------------+--------+-------
 Harbor Lights     |      0 |     5
 The Age of Canals |      0 |     5
(2 rows)

UPDATE 2

The problem upsert solves

Imagine a table that counts how many times each book was viewed today. The first view must insert a row; later views must update it. A plain insert fails on the second view:

pgsql · try it yourself
CREATE TABLE daily_views (book_id integer PRIMARY KEY, views integer NOT NULL);
INSERT INTO daily_views VALUES (1, 1);
INSERT INTO daily_views VALUES (1, 1);
CREATE TABLE
INSERT 0 1
ERROR:  duplicate key value violates unique constraint "daily_views_pkey"
DETAIL:  Key (book_id)=(1) already exists.

INSERT … ON CONFLICT DO UPDATE

ON CONFLICT (column) names the unique column (or constraint) to watch. DO UPDATE SET … says what to do instead; the special table EXCLUDED holds the row you tried to insert:

pgsql · try it yourself
CREATE TABLE daily_views (book_id integer PRIMARY KEY, views integer NOT NULL);

INSERT INTO daily_views VALUES (1, 1), (3, 1)
ON CONFLICT (book_id) DO UPDATE SET views = daily_views.views + EXCLUDED.views;

INSERT INTO daily_views VALUES (1, 1), (5, 1)
ON CONFLICT (book_id) DO UPDATE SET views = daily_views.views + EXCLUDED.views
RETURNING book_id, views;

SELECT * FROM daily_views ORDER BY book_id;
CREATE TABLE
INSERT 0 2
 book_id | views
---------+-------
       1 |     2
       5 |     1
(2 rows)

INSERT 0 2
 book_id | views
---------+-------
       1 |     2
       3 |     1
       5 |     1
(3 rows)

The second insert updated book 1 (now 2 views) and inserted book 5, in one atomic statement that is safe even when many sessions run it at once.

ON CONFLICT DO NOTHING

To simply skip rows that already exist, use DO NOTHING. The command tag shows how many rows were actually inserted:

pgsql · try it yourself
INSERT INTO categories (name)
VALUES ('Fiction'), ('Travel'), ('Mystery'), ('Art')
ON CONFLICT (name) DO NOTHING
RETURNING id, name;
 id |  name
----+--------
  9 | Travel
 11 | Art
(2 rows)

INSERT 0 2

Only the two new categories were inserted; the existing ones were silently skipped.

A conditional upsert

DO UPDATE can have a WHERE clause. Here a price feed only updates a book when the new price is actually different, so unchanged rows are not rewritten and are not reported back:

pgsql · try it yourself
CREATE TABLE price_list (book_id integer PRIMARY KEY, price numeric(6,2));
INSERT INTO price_list SELECT id, price FROM books WHERE id <= 3;

INSERT INTO price_list (book_id, price)
VALUES (1, 14.99), (2, 11.50), (3, 18.00), (4, 16.75)
ON CONFLICT (book_id) DO UPDATE
SET price = EXCLUDED.price
WHERE price_list.price IS DISTINCT FROM EXCLUDED.price
RETURNING book_id, price;
CREATE TABLE
INSERT 0 3
 book_id | price
---------+-------
       2 | 11.50
       4 | 16.75
(2 rows)

INSERT 0 2

Books 1 and 3 had the same price, so nothing happened to them; book 2 was updated and book 4 inserted.

MERGE

The SQL-standard MERGE statement combines insert, update and delete decisions against a source table. It is more verbose but more flexible than ON CONFLICT:

pgsql · try it yourself
CREATE TABLE stock_feed (book_id integer, delta integer);
INSERT INTO stock_feed VALUES (1, 5), (2, 3), (99, 1);

MERGE INTO books b
USING stock_feed f ON f.book_id = b.id
WHEN MATCHED THEN UPDATE SET stock = b.stock + f.delta
WHEN NOT MATCHED THEN DO NOTHING
RETURNING merge_action(), b.id, b.stock;
CREATE TABLE
INSERT 0 3
 merge_action | id | stock
--------------+----+-------
 UPDATE       |  1 |    17
 UPDATE       |  2 |     3
(2 rows)

MERGE 2

Test yourself

What does the EXCLUDED table contain in ON CONFLICT DO UPDATE?

  1. The existing row
  2. The row that was proposed for insertion
  3. Deleted rows
  4. All conflicting rows in the table

What does INSERT ... ON CONFLICT DO NOTHING do with duplicates?

  1. Raises an error
  2. Skips them silently
  3. Updates them
  4. Deletes the old row

Which clause returns the generated id from an INSERT?

  1. OUTPUT id
  2. RETURNING id
  3. SELECT LAST_ID()
  4. WITH id