Sub topic 2
Capturing deleted rows with DELETE ... RETURNING
This chapter assumes you know basic SQL, have a tasks table with an id primary key and a status column, and can run queries in psql. The tasks table comes from the earlier chapter on INSERT ... RETURNING. A DELETE with a RETURNING clause removes rows and sends back the deleted rows in the same statement. You do not need a SELECT before the delete to find out what was removed.
Deleting rows and returning them
Add RETURNING after the WHERE clause. The output lists each row as it was just before deletion.
DELETE FROM tasks
WHERE status = 'done'
RETURNING id, title, status;If the WHERE clause matches nothing, the statement deletes nothing and returns zero rows.
Expressions, aliases and * in the RETURNING list
RETURNING accepts any expression that SELECT accepts. You can add aliases with AS, and * returns every column.
DELETE FROM tasks
WHERE status = 'done'
RETURNING id, upper(title) AS shouted_title, now() - updated_at AS age;
DELETE FROM tasks
WHERE id = 7
RETURNING *;Use * only for quick checks. Listing columns explicitly keeps your code working if someone adds a column to the table later.
Reading RETURNING results from application code
Most drivers return the rows of a DELETE ... RETURNING as a result set, the same as a SELECT. This Python example uses psycopg 3:
import psycopg
with psycopg.connect("dbname=demo") as conn:
with conn.cursor() as cur:
cur.execute(
"DELETE FROM tasks WHERE status = %s RETURNING id, title",
("done",),
)
deleted = cur.fetchall()
print(f"Deleted {len(deleted)} rows: {deleted}")The with block commits the transaction when it exits without an error.
Chaining with a data-modifying CTE
A data-modifying common table expression (CTE) is a WITH query that contains a DELETE, INSERT or UPDATE. Here, the rows deleted from tasks move into an archive table in one atomic statement.
CREATE TABLE IF NOT EXISTS 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;Either both steps happen or neither does, so no task is lost between the delete and the insert.
Exercise
Exercise
You want to delete the task with id 7 and log its title in one statement. Which statement do you write, and what does it return?
Show answer
DELETE FROM tasks WHERE id = 7 RETURNING id, title; It returns one row with the id and title of the deleted task, or zero rows if no task has id 7.