Full answer
sql
CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tags (name) VALUES ('sql'), ('joins') RETURNING id, name;| id | name |
|---|---|
| 1 | sql |
| 2 | joins |
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;| id | qty |
|---|---|
| 2 | 8 |
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;| id | name |
|---|---|
| 1 | sql |
| 2 | joins |
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