// SQL snippet

Reserve the next job id

Sequences hand out ids atomically; RETURNING, OUTPUT and friends read them back.

Main statement
PostgreSQL
还支持
SQL Server MySQL

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.

PostgreSQL
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 Server
INSERT INTO jobs (name, created_at, status)
OUTPUT inserted.id
VALUES ('daily-report', SYSDATETIME(), 'pending');

MySQL: LAST_INSERT_ID()

MySQL
INSERT 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

// snippets are better with a schema brain

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.