Sub topic 15
Getting Changed Rows Back with `RETURNING`
Assume you know basic SELECT, WHERE, primary keys, and the difference between inserting, updating, and deleting rows. This chapter focuses on reading the rows affected by a data-change statement.
Why return changed rows?
An INSERT, UPDATE, or DELETE normally reports how many rows it changed. Sometimes an application also needs the actual rows. For example, after inserting a customer, it may need the database-generated ID. After updating an order, it may need the new status. After deleting records, it may need to record which IDs were removed.
PostgreSQL and SQLite support a RETURNING clause. It comes after the VALUES, SET, or WHERE part of the statement.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
status VARCHAR(20) NOT NULL,
total NUMERIC(10, 2) NOT NULL
);
INSERT INTO orders (id, status, total)
VALUES (100, 'new', 49.99)
RETURNING id, status, total;The statement changes the row and returns its selected columns. A client can read the result just as it reads the result of a SELECT.
Returning updated and deleted rows
RETURNING evaluates the values affected by the operation. For an UPDATE, it returns the new values.
UPDATE orders
SET status = 'shipped'
WHERE id = 100
RETURNING id, status;For a DELETE, it returns the values of the rows just before they are removed.
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING id, total;The WHERE clause still controls which rows change. If no row matches, the statement succeeds but returns zero rows. This makes the result useful for checking whether an expected record existed.
You can also return expressions and rename them:
UPDATE orders
SET total = total * 1.10
WHERE status = 'new'
RETURNING id, total AS adjusted_total;Returning rows does not make a change reversible. Use a transaction when the application must inspect the result and decide whether to keep the change.
Dialect differences
SQL Server uses OUTPUT instead of RETURNING:
DELETE FROM orders
OUTPUT deleted.id, deleted.total
WHERE status = 'cancelled';In SQL Server, deleted refers to values removed by DELETE, while inserted refers to new values produced by INSERT or UPDATE.
MySQL commonly requires a separate SELECT when an application needs changed rows. That approach must account for concurrency, because another transaction could change the data between the write and the query. Check your database version and driver before depending on a dialect-specific feature.
| Database | Common syntax | Typical use |
|---|---|---|
| PostgreSQL | `RETURNING` | Return inserted, updated, or deleted rows |
| SQLite | `RETURNING` | Return affected rows |
| SQL Server | `OUTPUT` | Return `inserted` or `deleted` values |
Exercise
What does a DELETE ... RETURNING id statement return when three rows match its WHERE clause?
Show answer
It deletes the three matching rows and returns their three IDs. If no rows match, it returns zero rows.