Concept · Modifying data

RETURNING with INSERT, UPDATE and DELETE

RETURNING gives back values from the rows a statement has just inserted, updated or deleted. Its availability and alternatives depend on the engine.

Before continuing: This entry is part of the UPDATE guide. If you are new to the topic, start with UPDATE.

Example

This example uses an integer key generated by SQLite. The same pattern is common in PostgreSQL when the id comes from an identity column, a sequence or a default value.

SQL verified in SQLite
CREATE TEMP TABLE orders_returning (
  id INTEGER PRIMARY KEY,
  customer TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending'
);

INSERT INTO orders_returning (customer)
VALUES ('Amy')
RETURNING id, customer, status;

The value pending comes from DEFAULT and the id is assigned by the table. There is no need to guess those values or run another lookup to get them back.

What changes from case to case

UPDATE and DELETE with RETURNING

With UPDATE, plain column references give the state after the change. With DELETE, they give the data of the row being deleted.

Update and return
UPDATE orders_returning
SET status = 'shipped'
WHERE id = 1
RETURNING id, status;
Result of the UPDATE
idstatus
1shipped
Delete and return
DELETE FROM orders_returning
WHERE id = 1
RETURNING id, customer, status;
Row returned before disappearing from the table
idcustomerstatus
1Amyshipped

RETURNING does not replace SELECT

RETURNING answers one very specific question: “which values did this change produce?”. A SELECT is still the tool for querying the overall state of a table, joining it to others or retrieving information later on.

Rule of thumb: uses RETURNING to get the immediate result of the change; use SELECT to query data as a separate operation.

Key differences between engines

PostgreSQL documents RETURNING for INSERT, UPDATE, DELETE and also MERGE. SQLite supports it in top-level statements INSERT, UPDATE and DELETE from version 3.35.0 and points out that it is not part of standard SQL.

Also, do not assume that RETURNING output can be reused inside another query the same way on every engine: SQLite documents restrictions that do not match PostgreSQL's capabilities. When portability matters, treat this clause as an engine-specific feature.