Sub topic 3
RETURNING with ON CONFLICT: what comes back and what does not
This chapter assumes you know INSERT, UPDATE and DELETE, primary keys, column defaults, and psql. It also assumes you know ON CONFLICT, which turns a unique-key collision into an update or a skipped row instead of an error.
Upserts with RETURNING
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL UNIQUE,
status text NOT NULL DEFAULT 'open',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO tasks (title)
VALUES ('Review PR')
ON CONFLICT (title) DO UPDATE
SET updated_at = now()
RETURNING id, title, updated_at;With DO UPDATE, RETURNING gives one row whether the insert path or the update path ran.
With DO NOTHING, a conflicting row is skipped and produces no output. If you insert three titles and one already exists, you get two rows back. The order of those rows is not guaranteed.
Joined tables with FROM
CREATE TABLE owners (
title text PRIMARY KEY,
team text NOT NULL
);
UPDATE tasks AS t
SET status = 'done'
FROM owners AS o
WHERE o.title = t.title
RETURNING t.id, t.title, o.team;RETURNING can read columns from the FROM or USING table. Only rows that match the join are returned.
Defaults, generated columns and triggers
RETURNING shows the row as stored. Defaults and generated columns are already computed, so updated_at appears with its real value. A BEFORE trigger that changes the new row is reflected in RETURNING. An AFTER trigger that changes the row is not.
MERGE ... RETURNING (PostgreSQL 17+)
MERGE INTO tasks AS t
USING (VALUES ('Review PR', 'done')) AS s(title, status)
ON t.title = s.title
WHEN MATCHED THEN
UPDATE SET status = s.status
WHEN NOT MATCHED THEN
INSERT (title, status) VALUES (s.title, s.status)
RETURNING merge_action(), t.id, t.title, t.status;merge_action() reports whether each row was inserted, updated or deleted.
RETURNING OLD and NEW (PostgreSQL 18+)
UPDATE tasks
SET status = 'done'
WHERE id = 1
RETURNING old.status AS previous_status, new.status AS current_status;Common mistakes
- Expecting a row back for every input row when you use DO NOTHING.
- Relying on the order of RETURNING rows.
- Updating the same row twice in one
ON CONFLICTstatement. PostgreSQL raises "command cannot affect row a second time." - Treating an UPDATE that matches no rows as an error. It returns zero rows.
Exercise
You run INSERT INTO tasks (title) VALUES ('A'), ('B'), ('Review PR') ON CONFLICT (title) DO NOTHING RETURNING id, title;. The title 'Review PR' already exists. How many rows come back?
Show answer
Two rows, for 'A' and 'B'. The conflicting row is skipped and produces no output.