// dialect comparison

Auto-incrementing primary keys

Five engines, five spellings of the column that numbers itself.

Filed under Tables & schema

The verdict

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.

Where they differ

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.

How each engine writes it

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.

PostgreSQL

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.

MySQL

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.

SQLite

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.

Oracle

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.

Questions that come up

Is SERIAL deprecated in PostgreSQL?

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.

When does SQLite's AUTOINCREMENT matter?

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.

What is the difference between IDENTITY and SEQUENCE in SQL Server?

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.

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.