Sub topic 1
What RETURNING does and why it replaces a follow-up SELECT
Prerequisites
This chapter assumes you can already do the following:
- Write basic
SELECT,INSERT,UPDATEandDELETEstatements. - Create a table with a primary key and column defaults.
- Run statements in
psqlor another PostgreSQL client.
You do not need to know anything about triggers, CTEs or upserts yet. Later chapters cover those. This chapter explains the core idea that the rest of the tutorial builds on.
The problem: write first, read second
A write statement normally tells you only how many rows it touched. Suppose you insert a task into a table where the database generates the key:
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 ('Write report');psql answers with INSERT 0 1, which means one row was inserted. It does not tell you the id that PostgreSQL generated, the status default, or the updated_at timestamp. Your application usually needs at least the id.
The naive fix is a second statement:
SELECT id, status, updated_at
FROM tasks
WHERE title = 'Write report';This works only when you have a reliable way to find the row again. Here title is unique, so it happens to work. In many tables there is no such natural key, and developers fall back on SELECT max(id), which is wrong. Other sessions can insert rows between your two statements, so you can read someone else's row.
What RETURNING does
RETURNING is a clause you add to the end of INSERT, UPDATE or DELETE. It makes the statement produce a result set, like a SELECT would, with one row for each row the statement changed. PostgreSQL 17 added the same clause to MERGE.
INSERT INTO tasks (title)
VALUES ('Review PR'), ('Plan sprint')
RETURNING id, title, status;In psql the output looks like this:
id | title | status
----+-------------+--------
2 | Review PR | open
3 | Plan sprint | open
(2 rows)
INSERT 0 2The id and status columns were never in your VALUES list. PostgreSQL filled them in, and RETURNING reported what it stored. The usual command tag (INSERT 0 2) still appears after the rows.
The general shape is:
INSERT ... RETURNING output_expression [ [ AS ] output_name ] [, ...]
UPDATE ... RETURNING output_expression [ [ AS ] output_name ] [, ...]
DELETE ... RETURNING output_expression [ [ AS ] output_name ] [, ...]For now, treat the list after RETURNING as a SELECT list. Expressions, aliases and * get their own chapter.
Why this replaces a follow-up SELECT
A second query is not just slower. RETURNING fixes three separate problems.
One round trip instead of two
Each statement sent from an application waits for the network and the server. With RETURNING, the write and the read happen in one request. This matters most when you insert in a loop, or when the database is far from the application.
The result describes your change and nothing else
The rows returned are the rows this statement changed. They are not a fresh look at the table. This removes two races that a follow-up SELECT has.
- Finding the wrong row. With
max(id)or a similar lookup, another session's insert can slip in between your statements. - Reading a later version. Under the default
READ COMMITTEDisolation level, each statement takes a new snapshot. If another session updates your row between yourUPDATEand yourSELECT, theSELECTshows their change, not yours.
Deleted rows can be recovered
After a DELETE, the rows are gone, so a follow-up SELECT cannot read them. You would have to SELECT first and then DELETE, and a concurrent change could make those two disagree. DELETE ... RETURNING hands you exactly the rows that were removed.
DELETE FROM tasks
WHERE status = 'done'
RETURNING *;The diagram contrasts the two approaches.
What values come back
The values depend on the statement type. Learn this table, because it is the main rule for reading RETURNING output.
| Statement | Row that `RETURNING` reads | Rows returned |
|---|---|---|
| `INSERT` | The new row as stored | One per inserted row |
| `UPDATE` | The new row, after the changes | One per updated row |
| `DELETE` | The row as it was before deletion | One per deleted row |
For INSERT and UPDATE, "as stored" includes column defaults, identity values and any change made by a BEFORE trigger. Changes made later by AFTER triggers are not visible. The chapter on defaults and triggers covers this in detail.
Here is an update that shows the new values:
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE title = 'Write report'
RETURNING id, status, updated_at; id | status | updated_at
----+--------+-------------------------------
1 | done | 2026-11-27 21:04:08.627+00
(1 row)
UPDATE 1You see the row after the update. If you also want the previous values, that needs RETURNING OLD on PostgreSQL 18 or later, or a different technique on earlier versions. A later chapter covers both.
When no row matches
If the WHERE clause matches nothing, the statement succeeds and returns an empty result set. It is not an error.
UPDATE tasks
SET status = 'done'
WHERE title = 'No such task'
RETURNING id; id
----
(0 rows)
UPDATE 0Application code must handle this case. A missing row is a valid outcome, and treating it as an error or reading rows[0] without checking will cause bugs.
RETURNING is not a SELECT
A few differences are worth knowing early:
RETURNINGis part of the write statement. You cannot attach it to a plainSELECT.- It is evaluated for each affected row, after the change is made inside the statement.
- If the statement fails, for example with a unique-constraint violation, no rows are returned and the error is raised instead.
- Returned values are not committed values. If you wrap the statement in a transaction and later roll back, the
idyou received refers to a row that no longer exists. Do not hand it out to other systems until the transaction commits. - Identity and sequence values are consumed even when a transaction rolls back, so rolled-back inserts leave gaps in the numbering.
RETURNINGdoes not change that.
Version notes
RETURNING on INSERT, UPDATE and DELETE has been in PostgreSQL for many years, so you can rely on it on any supported version. Two newer features extend it:
- PostgreSQL 17:
MERGEacceptsRETURNING, along with themerge_action()function. - PostgreSQL 18:
RETURNINGcan refer tooldandnewrow versions.
Later chapters cover both. Check SELECT version(); before using them.
Summary of the working model
- You send one write statement with a
RETURNINGlist. - PostgreSQL makes the change and evaluates the list against each affected row.
- The client receives a result set, followed by the usual command tag.
- Zero affected rows means a valid, empty result.
Exercise
A developer inserts an order with INSERT INTO orders (customer_id) VALUES (7); and then runs SELECT max(id) FROM orders; to learn the new order id. Name one thing that can go wrong, and rewrite the insert so the second statement is unnecessary.
Show answer
Another session can insert an order between the two statements, so max(id) may return that session's id instead of yours. Use one statement: INSERT INTO orders (customer_id) VALUES (7) RETURNING id;. The returned id always belongs to the row this statement inserted.
Exercise
You run UPDATE tasks SET status = 'done' WHERE id = 999 RETURNING id, status; and no task has id 999. What does the client receive, and does PostgreSQL raise an error?
Show answer
PostgreSQL raises no error. The client receives an empty result set (0 rows) with the command tag UPDATE 0. Application code should check for an empty result instead of assuming a row exists.