Sub topic 3
Reading results with RETURNING
This chapter assumes you know basic SQL, primary keys, unique constraints, and how to run statements in psql.
Reading results with RETURNING
RETURNING makes an INSERT or UPDATE return the rows it wrote. With ON CONFLICT DO NOTHING, skipped rows are not returned, so the result shows only what was inserted.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5), ('C-300', 2)
ON CONFLICT (sku) DO NOTHING
RETURNING sku, quantity;If A-100 already exists, only the C-300 row comes back. A DO UPDATE with a false WHERE clause also returns nothing for that row.
Upserting many rows in one statement
You can pass several rows in one VALUES list. The statement cannot propose the same key twice, or PostgreSQL raises an error. Merge duplicates first with GROUP BY.
Why upserts are safe under concurrency
A SELECT followed by an INSERT is a race. Two sessions can both see no row, then both insert, and one fails with a unique violation. ON CONFLICT checks and inserts in one atomic step. If another transaction has inserted the key but not committed, the second statement waits for that transaction, then takes the conflict path.
INSERT ON CONFLICT versus MERGE
MERGE (PostgreSQL 15 and later) can express the same upsert with a join condition. Under concurrent writers, MERGE can still raise a unique violation. For upserts keyed on a unique column, use INSERT ... ON CONFLICT. Use MERGE when you need its extra branches, such as WHEN MATCHED THEN DELETE.
Pitfalls: NULLs, sequence gaps, and dead tuples
- NULLs: By default, NULLs are distinct in a unique index, so rows with a NULL key never conflict.
- Sequence gaps: An identity value is consumed when the insert is attempted, even if
ON CONFLICTskips the row. Expect gaps in IDs. - Dead tuples:
DO UPDATEwrites a new row version and leaves the old one dead untilVACUUMremoves it. Upserting the same hot rows often causes table bloat.
Exercise
Table productstock has sku as its primary key. You run INSERT INTO productstock (sku, quantity) VALUES ('A-100', 5) ON CONFLICT (sku) DO NOTHING RETURNING sku; and A-100 already exists. What does the statement return?
Show answer
It returns zero rows. DO NOTHING skips the existing row, and RETURNING only includes rows that were inserted.