SQL Server
CREATE TABLE customers (
id INT IDENTITY(1, 1) PRIMARY KEY,
email VARCHAR(320)
);
IDENTITY(seed, step). Standalone SEQUENCE objects are the modern alternative when one counter must feed several tables.
Five engines, five spellings of the column that numbers itself.
Filed under Tables & schema
Write GENERATED ALWAYS AS IDENTITY on PostgreSQL and Oracle, IDENTITY on SQL Server and AUTO_INCREMENT on MySQL. On SQLite, plain INTEGER PRIMARY KEY is enough unless ids must never be reused.
SQL Server's IDENTITY predates the SQL standard's GENERATED … AS IDENTITY, which PostgreSQL (10+) and Oracle (12c+) use. MySQL keeps AUTO_INCREMENT. SQLite needs nothing extra: an INTEGER PRIMARY KEY column is an alias for the rowid and numbers itself, and AUTOINCREMENT only stops ids from being reused.
CREATE TABLE customers (
id INT IDENTITY(1, 1) PRIMARY KEY,
email VARCHAR(320)
);
IDENTITY(seed, step). Standalone SEQUENCE objects are the modern alternative when one counter must feed several tables.
CREATE TABLE customers (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT
);
The SQL-standard form, preferred over legacy SERIAL. ALWAYS forbids explicit ids; BY DEFAULT permits them.
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(320)
);
One AUTO_INCREMENT column per table and it must be indexed (the PK does it). innodb_autoinc_lock_mode tunes concurrency.
CREATE TABLE customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT
);
Plain INTEGER PRIMARY KEY already numbers itself as an alias for rowid, but may reuse the id of a deleted last row. AUTOINCREMENT prevents that reuse at a small cost.
CREATE TABLE customers (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR2(320)
);
12c+. Before 12c the pattern was a SEQUENCE plus a BEFORE INSERT trigger; 12c also allows DEFAULT customers_seq.NEXTVAL on a plain column.
Not deprecated, but identity columns (PostgreSQL 10+) are the recommended form: they are standard SQL, the sequence is owned and dropped with the column, and GRANTs on the table cover it. New tables should use GENERATED … AS IDENTITY.
Only when ids must never be reused. Without it, deleting the row with the highest id lets the next insert take that id again. AUTOINCREMENT records the highest id ever used in sqlite_sequence, which costs an extra write per insert.
IDENTITY belongs to one column of one table, and you can't update the column. A SEQUENCE (2012+) is a separate object: several tables can draw from it, you can fetch the next value before inserting, and you can restart it, much like an Oracle sequence.
Migrating data with its original ids: three engines make you ask first, two just accept the value.
You inserted the row; now get back the key the engine picked for it.
Two ways to empty a table that differ in speed, triggers, identity counters and rollback.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.