Full answer
Tables and rows used here:
sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int);
INSERT INTO stock VALUES ('PEN', 10);sql
INSERT INTO stock VALUES ('PEN', 5), ('INK', 3) ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty RETURNING sku, qty, (xmax = 0) AS inserted;PostgreSQL returns:
text
sku | qty | inserted
-----+-----+----------
PEN | 15 | f
INK | 3 | t
(2 rows)sql
INSERT INTO stock VALUES ('PAD', 1) ON CONFLICT (sku) DO NOTHING RETURNING sku; INSERT INTO stock VALUES ('PAD', 9) ON CONFLICT (sku) DO NOTHING RETURNING sku;Result on PostgreSQL 17:
text
sku
-----
(0 rows)PEN existed, so its quantity became 15 and inserted is false; INK was new, so inserted is true. In the second run, the first PAD insert succeeds, and the repeated insert with DO NOTHING returns no rows at all, since RETURNING only reports rows actually inserted or updated, which is a clean way to detect skipped duplicates. Only the last statement's result is shown, so the zero-row output belongs to the second PAD insert. The xmax test is an implementation detail that could change between versions.
sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int);
INSERT INTO stock VALUES ('PEN', 10);
INSERT INTO stock VALUES ('PEN', 5), ('INK', 3) ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty RETURNING sku, qty, (xmax = 0) AS inserted;
INSERT INTO stock VALUES ('PAD', 1) ON CONFLICT (sku) DO NOTHING RETURNING sku; INSERT INTO stock VALUES ('PAD', 9) ON CONFLICT (sku) DO NOTHING RETURNING sku;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- RETURNING works with upserts
- xmax = 0 identifies inserts
- DO NOTHING returns no row for skips
- The xmax trick relies on internals
- Wrap it in a tested helper
Common mistakes
- Running a SELECT before the upsert to decide, which races
- Depending on internals without tests
Follow-ups
- How would you count inserts versus updates in a batch?
- What does EXCLUDED refer to?
Tips
- Explain the zero-row result