← Back to SQL, page 10

sql-0190 · Medium mid

What does RETURNING do, and how would you use it after an INSERT?

RETURNING makes INSERT, UPDATE or DELETE return columns from the affected rows, such as a generated id or the new value, without a second query. PostgreSQL has long supported it; SQLite added it in 3.35. It avoids race-prone patterns like inserting and then selecting MAX(id).

Full answer
sql
CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tags (name) VALUES ('sql'), ('joins') RETURNING id, name;
idname
1sql
2joins

Both generated ids come back from the insert itself. RETURNING works with UPDATE and DELETE too:

sql
CREATE TABLE t2 (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO t2 VALUES (1, 5), (2, 7);
UPDATE t2 SET qty = qty + 1 WHERE id = 2 RETURNING id, qty;
idqty
28

PostgreSQL:

sql
CREATE TABLE tags (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text);
INSERT INTO tags (name) VALUES ('sql'), ('joins') RETURNING id, name;
idname
1sql
2joins

Selecting MAX(id) after an insert is wrong under concurrency, because another session may insert in between. RETURNING (or last_insert_rowid() in SQLite, which is per connection) avoids that.

sql
CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tags (name) VALUES ('sql'), ('joins') RETURNING id, name;

CREATE TABLE t2 (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO t2 VALUES (1, 5), (2, 7);
UPDATE t2 SET qty = qty + 1 WHERE id = 2 RETURNING id, qty;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • RETURNING returns columns from affected rows
  • Works with INSERT, UPDATE and DELETE
  • PostgreSQL and SQLite 3.35+ support it
  • Avoids SELECT MAX(id) after insert

Common mistakes

  • Reading MAX(id) to find a new row's id
  • Running a second query to see updated values

Follow-ups

  • How would you return old values from an UPDATE?
  • What is last_insert_rowid()?

Tips

  • Mention the concurrency problem it solves