Sub topic 12
RETURNING OLD and NEW (PostgreSQL 18+)
PostgreSQL 18 lets RETURNING read both the old and the new version of a row in the same statement. This chapter covers the syntax, what each statement puts in old and new, and the patterns this makes simple: change detection, audit rows and upsert diagnosis.
You should already know the basics of RETURNING from the earlier chapters, including UPDATE ... RETURNING, upserts and data-modifying CTEs (common table expressions). You also need a PostgreSQL 18 or later server and a client such as psql.
The problem this solves
Before version 18, RETURNING showed only one version of the row. For INSERT and UPDATE it was the row after the change. For DELETE it was the row that was removed. To learn what an UPDATE had overwritten, you had two options:
- Run a
SELECT ... FOR UPDATEfirst, then theUPDATE, and accept the extra round trip. - Join the table to itself in a CTE. This is awkward, and without a row lock it can read a value that another session changes before your update runs.
The new syntax removes both workarounds. The statement reports the old and new values from the same row version it just processed.
Check your server version first:
SHOW server_version_num;A value of 180000 or higher supports everything in this chapter. On older servers, old. and new. in RETURNING fail with an error.
Setup
The examples use the tasks table from earlier chapters. This script recreates it with sample data:
DROP TABLE IF EXISTS tasks CASCADE;
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, status)
VALUES ('Write report', 'open'),
('Review PR', 'open'),
('Plan sprint', 'blocked');Basic syntax: old and new
In the RETURNING list, old and new act as row aliases. You qualify a column with one of them, or use old.* and new.*:
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE title = 'Write report'
RETURNING old.status AS previous_status,
new.status AS current_status,
old.updated_at AS was_updated_at,
new.updated_at AS now_updated_at;The result is one row with previous_status = open and current_status = done.
An unqualified column name keeps its pre-18 meaning. For INSERT and UPDATE it means the new value. For DELETE it means the old value. Existing RETURNING clauses therefore behave exactly as before after an upgrade.
What old and new contain per statement
A statement cannot have an old row for something it creates, or a new row for something it removes. In those cases PostgreSQL still lets you write the reference. It supplies a row of all NULLs.
| Statement | `old` | `new` |
|---|---|---|
| `INSERT` | all NULL | the inserted row |
| `INSERT ... ON CONFLICT DO UPDATE`, inserted | all NULL | the inserted row |
| `INSERT ... ON CONFLICT DO UPDATE`, updated | the existing row | the updated row |
| `UPDATE` | the row before the update | the row after the update |
| `DELETE` | the deleted row | all NULL |
| `MERGE` | depends on the action taken | depends on the action taken |
Returning only rows that actually changed
RETURNING cannot filter rows. It reports every row the statement touched, including rows where the new value equals the old one. Compare the two versions in the select list to find real changes:
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE title IN ('Write report', 'Review PR')
RETURNING id,
old.status AS previous_status,
new.status AS current_status,
old.status IS DISTINCT FROM new.status AS status_changed;Write report is already done, so it comes back with status_changed = false. Review PR comes back with true. Use IS DISTINCT FROM instead of <>. A plain <> returns NULL when either side is NULL, which hides changes to or from NULL.
If you want to skip the unchanged rows entirely, put the test in the WHERE clause, as in WHERE status IS DISTINCT FROM 'done'. That also avoids writing a pointless new row version.
Renaming old and new with WITH
The default names old and new collide with a table or column that already has one of those names. You can pick other names with a WITH list at the start of RETURNING:
UPDATE tasks AS t
SET status = 'open', updated_at = now()
WHERE t.title = 'Plan sprint'
RETURNING WITH (OLD AS before, NEW AS after)
before.status AS status_before,
after.status AS status_after,
after.*;You can rename either alias, or both. Once you rename one, the default name stops working for it, so write before.status, not old.status.
Telling an insert from an update in an upsert
INSERT ... ON CONFLICT DO UPDATE returns a row for both outcomes, and plain RETURNING cannot say which one happened. Old and new answer that, because old is all NULL on the insert path:
INSERT INTO tasks (title, status)
VALUES ('Review PR', 'blocked'), ('Ship release', 'open')
ON CONFLICT (title) DO UPDATE
SET status = EXCLUDED.status, updated_at = now()
RETURNING id, title,
old.id IS NULL AS inserted,
old.status AS previous_status,
new.status AS current_status;Ship release comes back with inserted = true. Review PR comes back with inserted = false and its earlier status. Test a column that is NOT NULL in the table, such as the primary key. A nullable column would be NULL in an existing old row too, and the test would give a wrong answer.
This replaces the older xmax = 0 trick. That trick read an internal system column and depended on how PostgreSQL stores row versions. old.id IS NULL uses only documented behavior.
DELETE: the new row is empty
DELETE accepts new references, but they always return NULLs. That is rarely useful, and it is a quiet source of mistakes. In a combined query it looks like data is missing:
DELETE FROM tasks
WHERE status = 'done'
RETURNING old.id, old.title, new.title AS new_title;Every new_title is NULL because no new row exists. You usually write RETURNING * or old.* for a delete. The main use of new in DELETE is in shared SQL generated by tooling, where the same template covers all statement types.
Building an audit trail with a CTE
The best-known use is recording what changed. A data-modifying CTE takes the old and new values from the UPDATE and feeds them to an INSERT in one atomic statement:
CREATE TABLE task_history (
task_id bigint NOT NULL,
old_status text NOT NULL,
new_status text NOT NULL,
changed_at timestamptz NOT NULL DEFAULT now()
);
WITH changed AS (
UPDATE tasks
SET status = 'blocked', updated_at = now()
WHERE title = 'Review PR'
AND status IS DISTINCT FROM 'blocked'
RETURNING id, old.status AS old_status, new.status AS new_status
)
INSERT INTO task_history (task_id, old_status, new_status)
SELECT id, old_status, new_status FROM changed;The history row and the task change succeed or fail together. The WHERE condition keeps no-op updates out of the history. Compared with an audit trigger, this approach is explicit and visible in the query, but it only covers statements that include the CTE. A trigger covers every write path.
MERGE with old and new
On PostgreSQL 18, MERGE ... RETURNING can use old and new along with merge_action(). Each row follows the table's rules for the action taken. An insert has a NULL old, an update has both, and a delete has a NULL new.
MERGE INTO tasks AS t
USING (VALUES ('Review PR', 'done'), ('Archive docs', 'open')) AS s(title, status)
ON t.title = s.title
WHEN MATCHED THEN
UPDATE SET status = s.status, updated_at = now()
WHEN NOT MATCHED THEN
INSERT (title, status) VALUES (s.title, s.status)
RETURNING merge_action() AS action,
t.title,
old.status AS previous_status,
new.status AS current_status;The action column says UPDATE or INSERT. The old and new columns show the values on either side of that action.
Triggers and what the values reflect
The rules from the earlier trigger chapter still apply. new reflects the row after any BEFORE triggers have changed it, so it is the row that was stored. It does not show changes made later by AFTER triggers, which run after the row is written. Likewise, old is the row version the statement actually found and replaced.
Common mistakes
- Running on an older server. Statements using
old.ornew.fail on PostgreSQL 17 and earlier. Gate such code onserver_version_num. - Testing a nullable column to detect an insert. Use a
NOT NULLcolumn, normally the primary key. - Expecting only changed rows.
RETURNINGincludes rows whose values stayed the same. Compare withIS DISTINCT FROM, or filter inWHERE. - Reading
newin aDELETEoroldin a plainINSERT. These are always NULL. - Forgetting that unqualified names mean new for
INSERTandUPDATE. When the old value matters, qualify it. - Naming conflicts. If a table or column is called
oldornew, rename the aliases withWITH (OLD AS ..., NEW AS ...).
Exercise
You run an upsert on a table with primary key id, and you want one boolean column that is true when the row was inserted and false when an existing row was updated. Which RETURNING expression do you use, and why would old.title IS NULL be a risky choice if title is nullable?
Show answer
Use RETURNING old.id IS NULL AS inserted. On the insert path old is a row of all NULLs, and the primary key can never be NULL in a real existing row, so the test is reliable. If title is nullable, an existing row whose title is NULL would also give old.title IS NULL, so an update would be reported as an insert.
Exercise
Write an UPDATE that sets every 'open' task to 'in_progress' and returns each task's id together with its previous and new status.
Show answer
UPDATE tasks SET status = 'inprogress', updatedat = now() WHERE status = 'open' RETURNING id, old.status AS previousstatus, new.status AS currentstatus;