Upserts and RETURNING

Topic 3 of 5 in Changing data10 min readBeginnerFree course

Overview

Applications constantly face the same small problem: add this row, or if it’s already there, update it. A product feed sends the latest stock for each SKU; a counter goes up by one; a user’s settings are saved. Doing it in two steps — check whether the row exists, then insert or update — is slower and, worse, breaks when two requests arrive at the same moment. PostgreSQL’s answer is the upsert: INSERT … ON CONFLICT.

The race that upserts prevent

Imagine two web requests both recording stock for SKU LMP-01 at the same instant:

  1. Request A checks: no row for LMP-01.
  2. Request B checks: no row for LMP-01.
  3. Request A inserts it.
  4. Request B inserts it — and hits a duplicate-key error (or, without a unique key, creates a duplicate).

An upsert does the check and the write as one atomic operation, so this can’t happen.

Setting up

The examples use a small inventory table synced from a supplier, keyed by SKU:

SQL
CREATE TABLE inventory (
    sku        text PRIMARY KEY,
    quantity   integer NOT NULL CHECK (quantity >= 0),
    updated_at timestamp NOT NULL DEFAULT '2026-12-01'
);

INSERT INTO inventory (sku, quantity) VALUES ('LMP-01', 10), ('MUG-02', 4);
Text
CREATE TABLE
INSERT 0 2

ON CONFLICT DO NOTHING

The simplest upsert: insert the row, but if it would violate the unique key, quietly skip it.

SQL
INSERT INTO inventory (sku, quantity)
VALUES ('LMP-01', 99), ('KTL-03', 7)
ON CONFLICT (sku) DO NOTHING;
Text
INSERT 0 1

INSERT 0 1: KTL-03 was new and went in; LMP-01 already existed and was left alone. No error. This is perfect for “make sure this exists” jobs, such as loading reference data that may already be there.

ON CONFLICT DO UPDATE

More often you want the existing row updated. Inside DO UPDATE, the special table name EXCLUDED refers to the row you tried to insert:

INSERT … ON CONFLICT, the upsert. INSERT a row, for example a stock update. Is there a conflict on a unique key, ON CONFLICT (sku)? If not, the row is inserted. If yes, choose: DO NOTHING skips the row; DO UPDATE SET … updates the existing row, with EXCLUDED holding the new row; DO SELECT … RETURNING returns the existing row (PostgreSQL 19). Example: INSERT INTO inventory (sku, quantity) VALUES (‘LMP-01’, 5) ON CONFLICT (sku) DO UPDATE SET quantity = inventory.quantity + EXCLUDED.quantity RETURNING sku, quantity. It’s one atomic statement, safe under concurrency, with no check-then-insert race. MERGE is the standard-SQL cousin.

A delivery of 5 more lamps:

SQL
INSERT INTO inventory (sku, quantity)
VALUES ('LMP-01', 5)
ON CONFLICT (sku) DO UPDATE
    SET quantity   = inventory.quantity + EXCLUDED.quantity,
        updated_at = '2026-12-04'
RETURNING sku, quantity, updated_at;
Text
  sku   | quantity |     updated_at      
--------+----------+---------------------
 LMP-01 |       15 | 2026-12-04 00:00:00
(1 row)

INSERT 0 1

inventory.quantity is the value already in the table (10); EXCLUDED.quantity is the value from this insert (5). Running the same statement for a brand-new SKU would simply insert it.

To replace values rather than add to them — the usual case for a sync from another system — set the column to EXCLUDED.column:

SQL
INSERT INTO inventory (sku, quantity)
VALUES ('MUG-02', 12), ('TIN-04', 30)
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity
RETURNING sku, quantity;
Text
  sku   | quantity 
--------+----------
 MUG-02 |       12
 TIN-04 |       30
(2 rows)

INSERT 0 2

One statement updated MUG-02 and inserted TIN-04.

A WHERE on DO UPDATE makes the update conditional — for example, only overwrite if the incoming data is newer, or only if something actually changed (which avoids writing rows needlessly):

SQL
INSERT INTO inventory (sku, quantity)
VALUES ('KTL-03', 7)
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity
WHERE inventory.quantity IS DISTINCT FROM EXCLUDED.quantity;
Text
INSERT 0 0

INSERT 0 0: the quantity was already 7, so nothing was written.

The conflict target (sku) must match a unique index or constraint — a primary key, a UNIQUE column, or a unique index on several columns, such as ON CONFLICT (order_id, product_id).

ON CONFLICT DO SELECT (PostgreSQL 19)

A common need is “give me this row’s id, inserting it if it doesn’t exist yet”. With DO NOTHING, RETURNING returns nothing for a row that already existed, so you’d need a second query. PostgreSQL 19 adds DO SELECT, which returns the existing row instead:

SQL
INSERT INTO categories (name)
VALUES ('Tea')
ON CONFLICT (name) DO SELECT
RETURNING id, name;
Text
 id | name 
----+------
  2 | Tea
(1 row)

INSERT 0 1

Tea already exists, so you get its id (2) back — no error, no duplicate, no second query. (On PostgreSQL 18 and earlier this is a syntax error; there, use DO UPDATE SET name = EXCLUDED.name RETURNING id, which “touches” the row so that it’s returned.)

RETURNING everywhere

You’ve used RETURNING with INSERT. It works the same way with UPDATE and DELETE, returning the changed or removed rows:

SQL
UPDATE products
SET price = price + 0.50
WHERE category_id = 1
RETURNING id, name, price;
Text
 id |         name          | price 
----+-----------------------+-------
  1 | Ethiopian Yirgacheffe | 15.00
  2 | Colombian Supremo     | 12.50
  3 | Decaf House Blend     | 11.75
(3 rows)

UPDATE 3

Since PostgreSQL 18, RETURNING can show the values from before and after the change with old and new — ideal for audit logs and for telling the user what changed:

SQL
UPDATE products
SET stock = stock - 2
WHERE id = 9
RETURNING name, old.stock AS stock_before, new.stock AS stock_after;
Text
     name     | stock_before | stock_after 
--------------+--------------+-------------
 Burr Grinder |            6 |           4
(1 row)

UPDATE 1

Data-modifying CTEs

Because INSERT, UPDATE and DELETE with RETURNING produce rows, they can be used inside a WITH. That lets one statement do several connected changes — for example, move cancelled orders into an archive table and delete them, atomically:

SQL
CREATE TABLE cancelled_orders (LIKE orders);

WITH moved AS (
    DELETE FROM orders
    WHERE status = 'cancelled'
    RETURNING *
)
INSERT INTO cancelled_orders
SELECT * FROM moved
RETURNING id, customer_id, status;
Text
CREATE TABLE
 id | customer_id |  status   
----+-------------+-----------
  5 |           4 | cancelled
 15 |           6 | cancelled
(2 rows)

INSERT 0 2

(CREATE TABLE … (LIKE orders) makes an empty table with the same columns.) Either both steps happen or neither does.

MERGE

MERGE is the SQL-standard statement for synchronising a table with a source: for each source row, decide whether to update, delete or insert. PostgreSQL has supported it since version 15:

SQL
MERGE INTO inventory AS i
USING (VALUES ('LMP-01', 0), ('MUG-02', 15), ('PAN-05', 3)) AS s(sku, quantity)
   ON i.sku = s.sku
WHEN MATCHED AND s.quantity = 0 THEN
    DELETE
WHEN MATCHED THEN
    UPDATE SET quantity = s.quantity
WHEN NOT MATCHED THEN
    INSERT (sku, quantity) VALUES (s.sku, s.quantity);

SELECT sku, quantity FROM inventory ORDER BY sku;
Text
MERGE 3
  sku   | quantity 
--------+----------
 KTL-03 |        7
 MUG-02 |       15
 PAN-05 |        3
 TIN-04 |       30
(4 rows)

The lamp (quantity 0) was removed, the mug updated, and the pan added. MERGE is more flexible than ON CONFLICT — it can delete, and match on any condition — while ON CONFLICT is simpler and is the better choice for straightforward upserts under heavy concurrency.

Other databases: ON CONFLICT is shared by PostgreSQL and SQLite. MySQL uses INSERT … ON DUPLICATE KEY UPDATE; SQL Server and Oracle use MERGE. RETURNING is PostgreSQL, SQLite, MariaDB and Oracle; SQL Server has OUTPUT.

Exercise

Counting product page views

The website counts how often each product page is viewed. Create a table product_views with product_id integer PRIMARY KEY and views integer NOT NULL. Then record four page views — product 1, product 5, product 1, product 1 — with four separate upsert statements: each inserts (product_id, 1), and on a conflict on product_id adds 1 to the existing count. Finish with a SELECT of all rows ordered by product_id. Product 1 should end with 3 views and product 5 with 1.

SQL
CREATE TABLE product_views (
  product_id integer PRIMARY KEY,
  views      integer NOT NULL
);

INSERT INTO product_views (product_id, views)
VALUES (1, 1)
ON CONFLICT ___;

Summary

  • INSERT … ON CONFLICT (key) DO NOTHING skips rows that would violate a unique key or primary key.
  • ON CONFLICT (key) DO UPDATE SET … updates the existing row instead; EXCLUDED holds the values you tried to insert.
  • An upsert is one atomic statement, so it is safe when many users write at once — unlike checking first, then inserting.
  • RETURNING works on INSERT, UPDATE and DELETE; since PostgreSQL 18 it can show old and new values, and PostgreSQL 19 adds ON CONFLICT DO SELECT.
  • MERGE applies inserts, updates and deletes from a source in one standard-SQL statement; data-modifying CTEs chain changes together.