iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL AUTO INCREMENT

Auto-increment columns generate the next integer for you on every INSERT. Perfect for surrogate primary keys.

Per-vendor syntax

DBSyntax
MySQL / MariaDBid INT PRIMARY KEY AUTO_INCREMENT
PostgreSQL — modernid INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY
PostgreSQL — legacyid SERIAL PRIMARY KEY
SQL Serverid INT PRIMARY KEY IDENTITY(1,1)
SQLiteid INTEGER PRIMARY KEY AUTOINCREMENT
Oracle 12c+id NUMBER GENERATED ALWAYS AS IDENTITY

Inserting without specifying the id

SQL
INSERT INTO customers (name, email)
VALUES ('Ada', 'ada@example.com');

Reading back the new id

DBFunction
MySQLSELECT LAST_INSERT_ID();
PostgreSQLINSERT … RETURNING id;
SQL ServerSELECT SCOPE_IDENTITY(); or OUTPUT INSERTED.id
SQLiteSELECT last_insert_rowid();

Gaps in the sequence are normal

Auto-increment values aren't recycled after a delete, and a rolled-back transaction "burns" the value it claimed. Expect 1, 2, 4, 5, 8, … — that's by design.

Tip: Use BIGINT for auto-increment in new schemas. INT tops out at 2.1 billion; BIGINT is effectively infinite.

Example

Example
CREATE TABLE customers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80)
);
Try it Yourself »

Exercise

MySQL syntax for auto-incrementing IDs.

id INT PRIMARY KEY

Test yourself

Q1. MySQL syntax is…
Q2. Postgres modern (ANSI) form is…
Q3. Rolled-back inserts leave gaps because…

Discussion

Loading…