Sub topic 4
Capturing Deleted Rows with DELETE ... RETURNING
This chapter assumes you can write basic SELECT, INSERT, UPDATE and DELETE statements. It also assumes you know what primary keys and column defaults are, and that you can run SQL in psql or another PostgreSQL client. Earlier chapters introduced the RETURNING clause. Here you apply it to DELETE, where it returns the rows as they were just before removal.
Why delete and read in one statement
A plain DELETE reports only a count, such as DELETE 3. If you need to know which rows disappeared, the obvious approach is a SELECT followed by a DELETE. That approach has two problems:
- Another session can insert or change rows between the two statements. The rows you read may differ from the rows you deleted.
- It costs two round trips to the server.
DELETE ... RETURNING removes the rows and hands them back in the same statement. What you receive is exactly what was deleted.
The basic form
The examples in this chapter use this table and data:
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', 'done'),
('Review PR', 'open'),
('Update docs', 'done'),
('Plan sprint', 'open');Now delete the finished tasks and ask for every column back:
DELETE FROM tasks
WHERE status = 'done'
RETURNING *;The result has one row for each deleted task, with its id, title, status and updated_at. In psql, the rows print first, then the command tag DELETE 2.
The values are those the row held when it was deleted. DELETE does not change columns, so nothing is "after" the delete. This differs from UPDATE ... RETURNING, which shows the new values.
When nothing matches
If the WHERE clause matches no rows, the statement succeeds and returns zero rows. It does not raise an error. Application code must handle an empty result, particularly when it deletes by id and expects exactly one row back.
DELETE FROM tasks
WHERE id = 999999
RETURNING id, title;This prints (0 rows) followed by DELETE 0.
If you omit the WHERE clause, every row is deleted and returned. On a large table that means a very large result set.
Choosing what to return
The RETURNING list accepts column names, expressions and aliases, as it does for other statements. Return only what the caller needs:
DELETE FROM tasks
WHERE status = 'open' AND updated_at < now() - interval '30 days'
RETURNING id, title, now() - updated_at AS age;Use * for quick work and logging. In application code, prefer an explicit column list. A later ALTER TABLE ... ADD COLUMN will not change the shape of a result that names its columns.
The privileges involved are worth knowing. You need DELETE on the table, and SELECT on any column you read in WHERE or RETURNING. A role with DELETE but no SELECT can still run a bare DELETE, and it will fail as soon as you add RETURNING *.
Common uses
Audit and undo
Returning deleted rows lets the application log what it removed. It also lets you offer an undo, because you hold the full row and can reinsert it:
BEGIN;
DELETE FROM tasks
WHERE title = 'Plan sprint'
RETURNING *;
-- Inspect the output. Then either COMMIT, or undo everything:
ROLLBACK;After ROLLBACK, the row is back in the table. The rows you saw were only a preview of a change that was never committed.
Taking items off a queue
A table can act as a work queue. A worker needs to claim one job and remove it atomically. RETURNING hands the job to the worker, and FOR UPDATE SKIP LOCKED keeps two workers from claiming the same one:
CREATE TABLE jobs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload text NOT NULL
);
INSERT INTO jobs (payload) VALUES ('send email'), ('resize image');
DELETE FROM jobs
WHERE id = (
SELECT id
FROM jobs
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED
)
RETURNING id, payload;DELETE has no LIMIT clause, so the subquery picks the single row. SKIP LOCKED makes a second worker skip any row that a first worker has locked and take the next one.
If the worker crashes after the delete and before it finishes the job, the job is lost, unless the delete and the work share one transaction. Use this pattern only when that fits your reliability needs.
Moving rows to an archive
You can feed the deleted rows into another statement with a data-modifying common table expression (CTE). A CTE is a named subquery introduced with WITH. This moves finished tasks to an archive table:
CREATE TABLE tasks_archive (
id bigint PRIMARY KEY,
title text NOT NULL,
status text NOT NULL
);
WITH removed AS (
DELETE FROM tasks
WHERE status = 'done'
RETURNING id, title, status
)
INSERT INTO tasks_archive (id, title, status)
SELECT id, title, status FROM removed;The whole statement is atomic. If the INSERT fails, for example on a duplicate key in the archive, the DELETE is undone and no task is lost.
Reading the result from application code
DELETE ... RETURNING produces a result set, so a client library treats it like a SELECT. In most drivers you call the query method, not an "execute without results" method, and then read the rows. A short example with Python and psycopg 3:
import psycopg
with psycopg.connect("dbname=app") as conn:
rows = conn.execute(
"DELETE FROM tasks WHERE status = %s RETURNING id, title",
("done",),
).fetchall()
for task_id, title in rows:
print(f"deleted {task_id}: {title}")Always pass values as parameters, as %s does here. Never build the WHERE clause by pasting strings together. An empty list means no rows matched.
Deleting with joins
DELETE ... USING lets the WHERE clause refer to other tables. RETURNING may then read columns from those tables as well as from the target:
DELETE FROM tasks AS t
USING tasks_archive AS a
WHERE t.title = a.title
RETURNING t.id, t.title, a.id AS archive_id;This removes tasks that already have an archived copy and shows both ids. Later chapters cover joined deletes in more depth.
Edge cases and surprises
| Situation | What RETURNING shows |
|---|---|
| `WHERE` matches nothing | Zero rows, no error |
| `BEFORE DELETE` trigger returns `NULL` | That row is skipped: not deleted and not returned |
| `AFTER DELETE` trigger | Rows are returned as deleted. The trigger cannot change the result |
| `ON DELETE CASCADE` on child tables | Only target-table rows are returned. Cascaded child rows are not |
| Row changed by a concurrent transaction | The latest committed version, if it still matches `WHERE` |
| No `ORDER BY` available | Row order is not guaranteed |
Four of these deserve a closer look.
Triggers. A row-level BEFORE DELETE trigger can cancel the deletion of a row by returning NULL. Since the row is not deleted, RETURNING does not include it. The DELETE n count and the number of returned rows stay equal. If the number of returned rows is smaller than you expected, check for triggers before you suspect your WHERE clause.
Cascades. A foreign key declared with ON DELETE CASCADE removes child rows silently. They are deleted by the constraint machinery, so they are not part of your RETURNING output. If you need them, delete from the child table first in a CTE and return its rows too:
WITH child_rows AS (
DELETE FROM task_comments
WHERE task_id = 1
RETURNING *
)
DELETE FROM tasks
WHERE id = 1
RETURNING (SELECT count(*) FROM child_rows) AS comments_removed, *;This assumes a task_comments table with a task_id foreign key.
Concurrency. At the default READ COMMITTED isolation level, a DELETE that finds a row locked by another transaction waits. When the lock is released, PostgreSQL re-checks the WHERE clause against the updated row. If the row still matches, it is deleted and the new version is returned. If it no longer matches, the row is skipped. The returned data can therefore differ from what a SELECT showed you a moment earlier.
Ordering. Rows come back in the order the executor processed them, which is not guaranteed. A CTE cannot be given an ORDER BY on its DELETE. If you need ordered output, select from the CTE with an ORDER BY:
WITH removed AS (
DELETE FROM tasks
WHERE status = 'done'
RETURNING id, title
)
SELECT * FROM removed ORDER BY id;Common mistakes
- Expecting new values.
DELETE ... RETURNINGshows the row before deletion. On PostgreSQL 18 and later,RETURNING old.*is also accepted, but the output is the same here, because a delete has no new row. - Running it as a command with no result. Some drivers discard rows unless you use the method that fetches results.
- Forgetting
SELECTprivilege.RETURNINGreads columns, so the role needsSELECTon them. - Using it to delete a huge table in one go. All deleted rows are held in the result, which uses memory on the server and the client. Delete in batches and return only the key columns.
Exercise
Write one statement that deletes every task from tasks whose status is 'done', copies those rows into tasksarchive, and returns nothing to the client. What happens to the deleted rows if the INSERT fails because an id already exists in tasksarchive?
Show answer
Use a data-modifying CTE: WITH removed AS (DELETE FROM tasks WHERE status = 'done' RETURNING id, title, status) INSERT INTO tasks_archive (id, title, status) SELECT id, title, status FROM removed; The outer INSERT has no RETURNING clause, so the client receives only the command tag. Because the whole statement is atomic, a duplicate key error in the INSERT rolls back the DELETE too, and the tasks remain in the tasks table.
Exercise
A DELETE with a WHERE clause that you know matches three rows returns only two rows from RETURNING, and the command tag says DELETE 2. Name one likely cause and how you would check it.
Show answer
A row-level BEFORE DELETE trigger returned NULL for one row, which cancelled that deletion. A row skipped this way is neither deleted nor returned. Check the table's triggers with \d tasks in psql, or query pg_trigger. A concurrent transaction that changed the third row so it no longer matched the WHERE clause can cause the same result.