Reserve the next job id
Sequences hand out ids atomically; RETURNING, OUTPUT and friends read them back.
The task
You need to insert a job and immediately know its id to reference it elsewhere. MAX(id) + 1 is a race waiting to happen.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
INSERT INTO jobs (name, created_at, status)
VALUES ('daily-report', NOW(), 'pending')
RETURNING id;
仕組み
The database's sequence allocates the id atomically as part of the insert; RETURNING gives the new row's id back in the same statement, so no second query and no race. The same RETURNING clause works on SQLite 3.35+. SQL Server uses OUTPUT INSERTED.id, MySQL reads LAST_INSERT_ID() on the same connection (it is per-connection, so other sessions' inserts do not affect it), and Oracle uses RETURNING id INTO a bind variable or PL/SQL variable.
Variations
SQL Server: OUTPUT
SQL ServerINSERT INTO jobs (name, created_at, status)
OUTPUT inserted.id
VALUES ('daily-report', SYSDATETIME(), 'pending');
MySQL: LAST_INSERT_ID()
MySQLINSERT INTO jobs (name, created_at, status)
VALUES ('daily-report', NOW(), 'pending');
SELECT LAST_INSERT_ID() AS id;
Questions that come up
Why is MAX(id) + 1 wrong?
Two sessions can read the same MAX before either inserts, both compute the same next id, and one insert fails or you get duplicates. Sequences (and identity/auto-increment columns) allocate atomically inside the engine, which is the whole point.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.