Full answer
sql
PRAGMA journal_mode = WAL;
CREATE TABLE web_orders2 (id INTEGER PRIMARY KEY, customer TEXT);The query as written:
sql
INSERT INTO web_orders2 (customer) VALUES ('Ana');
INSERT INTO web_orders2 (customer) VALUES ('Ben');
SELECT MAX(id) AS what_ana_thinks_is_hers FROM web_orders2;| what_ana_thinks_is_hers |
|---|
| 2 |
In this run, two inserts happen back to back, as two users' requests would in production. Ana's code then asks for MAX(id) and receives 2, which is Ben's order. Under concurrency, the gap between insert and select is enough for another insert to land.
A corrected version:
sql
INSERT INTO web_orders2 (customer) VALUES ('Chen') RETURNING id, customer;| id | customer |
|---|---|
| 3 | Chen |
RETURNING hands back the row that this statement inserted, with no second query and no race. last_insert_rowid() is also safe in SQLite because it is tracked per connection, and PostgreSQL's currval('seq') is per session; only MAX(id) and similar table-wide reads are unsafe. ORMs use these mechanisms internally.
sql
PRAGMA journal_mode = WAL;
CREATE TABLE web_orders2 (id INTEGER PRIMARY KEY, customer TEXT);
INSERT INTO web_orders2 (customer) VALUES ('Ana');
INSERT INTO web_orders2 (customer) VALUES ('Ben');
SELECT MAX(id) AS what_ana_thinks_is_hers FROM web_orders2;
INSERT INTO web_orders2 (customer) VALUES ('Chen') RETURNING id, customer;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- MAX(id) races with other inserts
- RETURNING gives the inserted row
- last_insert_rowid is per connection
- currval is per session in PostgreSQL
Common mistakes
- Using MAX(id) or COUNT(*) to find new ids
- Reading the id from a different connection
Follow-ups
- How would you get ids for a multi-row insert?
- What happens to last_insert_rowid after a failed insert?
Tips
- Point to the race window