// dialect comparison

Get the id of the row you just inserted

You inserted the row; now get back the key the engine picked for it.

Filed under Inserting & updating

The verdict

RETURNING in PostgreSQL and SQLite 3.35+ and OUTPUT in SQL Server get the key in the same statement. MySQL's LAST_INSERT_ID() works fine as long as you read it on the same connection, right after the insert.

Where they differ

Every engine can hand back a generated key. SQL Server's OUTPUT and the RETURNING clause of PostgreSQL and SQLite 3.35+ return a result set from the INSERT itself, which also works for multi-row inserts. MySQL needs a second statement, and Oracle's RETURNING INTO writes into a bind variable.

How each engine writes it

SQL Server

INSERT INTO customers (email)
OUTPUT INSERTED.id
VALUES ('[email protected]');

Returns one row per inserted row. On a table with triggers, plain OUTPUT fails; use OUTPUT … INTO a table variable. SCOPE_IDENTITY() returns the last identity value in the current scope.

PostgreSQL

INSERT INTO customers (email)
VALUES ('[email protected]')
RETURNING id;

RETURNING is a real result clause: multi-row, and available on UPDATE and DELETE too.

MySQL

INSERT INTO customers (email) VALUES ('[email protected]');
SELECT LAST_INSERT_ID();

Per connection, so other sessions' inserts don't affect it. After a multi-row insert it returns the first id generated, not the last. No RETURNING clause.

SQLite

INSERT INTO customers (email) VALUES ('[email protected]');
SELECT last_insert_rowid();

Per-connection scalar. SQLite 3.35+ also supports RETURNING directly on the INSERT.

Oracle

INSERT INTO customers (email)
VALUES ('[email protected]')
RETURNING id INTO :new_id;

RETURNING INTO fills a bind or PL/SQL variable (use RETURNING BULK COLLECT INTO for many rows); it does not return a result set. Identity columns need 12c+.

Questions that come up

Is LAST_INSERT_ID() safe with connection pooling?

Yes, if you read it on the same connection before returning it to the pool. It is scoped to the connection, not global. Most drivers expose it directly after the insert (for example, the insert id on the result object).

How do I get ids for a batch insert in SQL Server?

OUTPUT INSERTED.id returns one row per inserted row, so a 500-row insert gives 500 ids. SCOPE_IDENTITY() only knows the last one. Add other OUTPUT columns (OUTPUT INSERTED.id, INSERTED.email) to tell the rows apart.

What about sequences in Oracle or PostgreSQL?

Oracle: sequence_name.CURRVAL after a NEXTVAL in the same session. PostgreSQL: currval('sequence_name') or lastval(). With identity columns, RETURNING is simpler and can't pick up a value from a different sequence.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.