Sub topic 3
Seeing the new row values after UPDATE
This chapter assumes you can write a basic UPDATE ... WHERE, you know what a primary key and a column default are, and you can run statements in psql or another PostgreSQL client. The earlier chapters introduced RETURNING on INSERT. Here we look at what it does on UPDATE.
What UPDATE ... RETURNING gives you
An UPDATE normally reports only a command tag such as UPDATE 1, which is a count of rows. If you add a RETURNING clause, PostgreSQL also sends back one result row for every row the statement changed. Each result row shows the values after the update, in the same statement and the same transaction.
The chapter uses the tasks table from earlier. If you don't have it, create it and add two rows:
CREATE TABLE IF NOT EXISTS 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 ('Write report'), ('Review PR')
ON CONFLICT (title) DO NOTHING;Now mark one task as done and read the result:
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE title = 'Write report'
RETURNING id, status, updated_at;The output has one row with the task's id, the new status (done) and the new updated_at. Without RETURNING you would run a second SELECT to confirm the change. That costs a round trip, and another session could change the row between your two statements. With RETURNING, the values you read are exactly the values your statement wrote.
Which rows come back
RETURNING produces a row for each row the UPDATE actually modified. The rules follow from that.
| Situation | What RETURNING produces |
|---|---|
| `WHERE` matches one row | One row |
| `WHERE` matches several rows | One row per matched row |
| `WHERE` matches nothing | Zero rows, and no error |
| `SET` writes the same value that is already stored | The row is still returned, because it was still updated |
| A `BEFORE UPDATE` trigger returns `NULL` for a row | That row is skipped, so it is not returned |
The zero-row case matters in application code. "The statement succeeded" and "a row changed" are different facts. An empty result is how you detect that the id or title you supplied did not exist.
An update that touches many rows returns many rows:
UPDATE tasks
SET status = 'archived', updated_at = now()
WHERE status = 'done'
RETURNING id, title;The rows come back in no guaranteed order. RETURNING has no ORDER BY of its own. If you need an order, wrap the update in a data-modifying CTE (a WITH query that contains an UPDATE) and sort in the outer query:
WITH changed AS (
UPDATE tasks
SET status = 'archived', updated_at = now()
WHERE status = 'done'
RETURNING id, title
)
SELECT id, title
FROM changed
ORDER BY id;The next chapters cover CTEs in more detail.
Reading the new value of a computed column
RETURNING is most useful when the new value depends on the old one and you can't know it in advance. A counter is the standard case:
CREATE TABLE IF NOT EXISTS counters (
name text PRIMARY KEY,
value bigint NOT NULL DEFAULT 0
);
INSERT INTO counters (name) VALUES ('invoice')
ON CONFLICT (name) DO NOTHING;
UPDATE counters
SET value = value + 1
WHERE name = 'invoice'
RETURNING value;The expression value + 1 is evaluated by the server, and RETURNING value gives you the result. Two sessions running this at the same time each get a different number. The second one waits for the row lock held by the first, then re-reads the committed row and adds one to it. A pattern of "SELECT the value, add one in the application, UPDATE it back" cannot give that guarantee.
In RETURNING, an unqualified column name means the new value of that column. This also holds for columns you did not put in SET. They come back unchanged, as part of the row's new version.
Values set by triggers and defaults
RETURNING reads the row as it is stored at the end of the row's update, after any BEFORE UPDATE triggers have run. If a trigger changes a column, you see the trigger's value. This trigger overwrites updated_at whatever the statement says:
CREATE OR REPLACE FUNCTION touch_updated_at()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := clock_timestamp();
RETURN NEW;
END;
$$;
CREATE TRIGGER tasks_touch
BEFORE UPDATE ON tasks
FOR EACH ROW EXECUTE FUNCTION touch_updated_at();
UPDATE tasks
SET status = 'open'
WHERE title = 'Review PR'
RETURNING id, status, updated_at;The updated_at in the output comes from clock_timestamp() inside the trigger. You did not set it in the statement.
AFTER triggers behave differently. They run after the row is written, so any change they make to the same table happens as a separate update. RETURNING does not show that later change. If an AFTER trigger modifies the row you just updated, the values you got back may no longer match what is stored. Prefer BEFORE triggers for columns you want to read through RETURNING.
Generated columns (GENERATED ALWAYS AS (...) STORED) are recalculated during the update, and RETURNING shows the recalculated value.
Getting the old value before PostgreSQL 18
By default RETURNING shows only the new row. Often you also want to know what the value was before. PostgreSQL 18 added old and new aliases for this (a later chapter covers them). On earlier versions you can read the old value by locking the row first and joining to it in the UPDATE:
WITH before AS (
SELECT id, status
FROM tasks
WHERE id = 1
FOR UPDATE
)
UPDATE tasks AS t
SET status = 'done'
FROM before
WHERE t.id = before.id
RETURNING before.status AS previous_status, t.status AS current_status;Three details make this work:
FOR UPDATElocks the row, so no other session can change it between the read and the write.UPDATE ... FROMlets theRETURNINGlist use columns from the joinedbeforeresult as well as from the target table. The next-but-one chapters on joins cover this form.- The target table has an alias,
t, sot.statusis clearly the new value andbefore.statusis clearly the old one.
If you need this on PostgreSQL 18 or later, the old and new aliases are simpler. The workaround above is for older servers.
Ambiguous names and other errors
These are the mistakes people commonly make with UPDATE ... RETURNING.
- Assuming one row. Client code that reads "the" returned row will silently use the first row when several matched, or fail when none did. Check the row count.
- Ambiguous column names. With
UPDATE ... FROM, a column such asidmay exist in both tables. PostgreSQL then reportscolumn reference "id" is ambiguous. Qualify the name with the table alias. - Expecting the old value.
RETURNING statusis the new status. If you seedonewhere you expectedopen, this is why. - Expecting aggregates.
RETURNINGworks on one result row per changed row. You cannot writeRETURNING count(*). To get a count, use a CTE and aggregate in the outer query:
WITH changed AS (
UPDATE tasks
SET status = 'archived'
WHERE status = 'done'
RETURNING id
)
SELECT count(*) AS archived_count
FROM changed;- Relying on a
SELECTafterward. Another session can change the row between yourUPDATEand the followingSELECT.RETURNINGcloses that gap.
Summary of the behaviour
RETURNINGonUPDATEyields one row per updated row, showing the values after the update.- Zero matching rows give zero returned rows and no error.
- Expressions in
SETare evaluated on the server, soRETURNINGis the safe way to read computed results such as counters. BEFOREtriggers and generated columns are visible in the output. Later changes byAFTERtriggers are not.- Before PostgreSQL 18, the old value requires a locked
SELECTjoined in throughUPDATE ... FROM.
Exercise
The table counters has one row, name 'invoice', value 41. Write one statement that increases the value by 10 and returns both the counter name and the new value. What will the statement return if you change the WHERE clause to name = 'receipt', which does not exist?
Show answer
UPDATE counters SET value = value + 10 WHERE name = 'invoice' RETURNING name, value; This returns one row: invoice, 51. With name = 'receipt', the WHERE clause matches nothing, so the statement returns zero rows and raises no error. The command tag is UPDATE 0.
Exercise
A teammate wrote UPDATE tasks SET status = 'done' WHERE id = 1 RETURNING status; and says the output proves the task was 'open' before. Is the teammate right? How could you read both the previous and the current status on PostgreSQL 16?
Show answer
No. RETURNING shows the row after the update, so the output is always 'done' and says nothing about the earlier value. On PostgreSQL 16, lock the row in a CTE with SELECT id, status FROM tasks WHERE id = 1 FOR UPDATE, then run UPDATE tasks AS t SET status = 'done' FROM that CTE WHERE t.id = before.id RETURNING before.status AS previousstatus, t.status AS currentstatus; (name the CTE before). On PostgreSQL 18 you can write RETURNING old.status, new.status instead.