Auto-Increment and Identity

Updated · 9 min read
mediumPostgreSQL 18sqlidentityauto-incrementserialsequencereturning

An identity column numbers new rows for you: 1, 2, 3, and so on, so you never have to work out the next id yourself. The Fee Tracker's payment_id works this way. When a new payment is recorded, nobody looks up the highest id and adds one; the database hands out 8. That matters as soon as two people record payments at the same moment, because they'd both pick the same "next" number. This lesson covers identity columns, getting the new id back, why ids have gaps, the older SERIAL shorthand, the sequences underneath, and how other databases spell it.

In One Minute

  • id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY numbers new rows automatically. It's the SQL standard.
  • Leave the column out of the INSERT, and the database fills it in.
  • RETURNING id hands the new value back in the same statement.
  • Ids can have gaps: failed inserts and rollbacks use numbers up. That's normal.
  • SERIAL is PostgreSQL's older shorthand; MySQL uses AUTO_INCREMENT, SQL Server IDENTITY(1,1).

Identity Columns

SQL
column_name INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
column_name INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY

Navika's study log, numbered by the database:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  student_id INTEGER NOT NULL,
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_sessions (student_id, minutes)
VALUES (103, 45), (101, 90)
RETURNING *;
Output
CREATE TABLE
 
 session_id | student_id | minutes
------------+------------+---------
          1 |        103 |      45
          2 |        101 |      90
(2 rows)

The INSERT named only student_id and minutes, and the database numbered the rows 1 and 2. Behind the scenes, an identity column is backed by a sequence, a counter that hands out the next number each time it's asked.

Each INSERT takes the next number from the counter: 1, 2, 3

ALWAYS or BY DEFAULT

GENERATED ALWAYS refuses a value you type in; GENERATED BY DEFAULT accepts one. With ALWAYS, choosing your own id is an error:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  student_id INTEGER NOT NULL,
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_sessions (session_id, student_id, minutes)
VALUES (10, 103, 45);
Output
CREATE TABLE
 
ERROR:  cannot insert a non-DEFAULT value into column "session_id"
DETAIL:  Column "session_id" is an identity column defined as GENERATED ALWAYS.
HINT:  Use OVERRIDING SYSTEM VALUE to override.

The hint names the escape hatch, OVERRIDING SYSTEM VALUE, which is meant for special jobs such as copying rows from another database. The Fee Tracker uses BY DEFAULT instead, so its setup script can insert payments with known ids. The catch: the counter doesn't know about ids you typed yourself. Insert payment 8 by hand, then let the database choose, and it picks 8 too:

SQL▶ Try it
INSERT INTO payments (payment_id, student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (8, 103, 5, 25.00, '2026-01-05', '2026-01-05', 'card');
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (103, 5, 25.00, '2026-01-05', '2026-01-05', 'card');
Output
INSERT 0 1
 
ERROR:  duplicate key value violates unique constraint "payments_pkey"
DETAIL:  Key (payment_id)=(8) already exists.

Getting the New Id Back

RETURNING hands back values from the rows an INSERT just wrote, so you learn the new id without a second query:

SQL▶ Try it
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (103, 5, 25.00, '2026-01-05', '2026-01-05', 'card')
RETURNING payment_id;
Output
 payment_id
------------
          8
(1 row)

The program recording the payment can now print "Receipt for payment 8" or store 8 in a related row. Never find the new id with SELECT max(payment_id): if two payments are recorded at the same moment, both programs can read the same maximum. RETURNING is PostgreSQL only among the big four; MySQL uses SELECT LAST_INSERT_ID() after the insert, SQL Server uses SCOPE_IDENTITY() or an OUTPUT clause, and Oracle uses RETURNING ... INTO in PL/SQL.

Why Ids Have Gaps

A number taken from the sequence is never given back, even when the row isn't saved. Here an INSERT of two rows fails on its second row, after both had already taken numbers:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  student_id INTEGER NOT NULL,
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_sessions (student_id, minutes) VALUES (103, 45);
INSERT INTO study_sessions (student_id, minutes) VALUES (103, 20), (103, NULL);
INSERT INTO study_sessions (student_id, minutes) VALUES (101, 90)
RETURNING *;
Output
CREATE TABLE
 
INSERT 0 1
 
ERROR:  null value in column "minutes" of relation "study_sessions" violates not-null constraint
DETAIL:  Failing row contains (3, 103, null).
 
 session_id | student_id | minutes
------------+------------+---------
          4 |        101 |      90
(1 row)

The failed statement used up 2 and 3, so the next row got 4. Rollbacks and deleted rows leave gaps the same way. This is deliberate: never reusing a number lets many sessions take ids at once without waiting for each other.

The failed INSERT used 2 and 3; the next successful row gets 4

Sequences Underneath

A sequence is a standalone counter. You can make one yourself, for example for receipt numbers that start at 1000 and go up by 10:

SQL▶ Try it
CREATE SEQUENCE receipt_numbers START WITH 1000 INCREMENT BY 10;
 
SELECT nextval('receipt_numbers') AS first_receipt,
       nextval('receipt_numbers') AS second_receipt;
Output
CREATE SEQUENCE
 
 first_receipt | second_receipt
---------------+----------------
          1000 |           1010
(1 row)

nextval takes the next number; currval repeats the last number this session took. Identity columns accept the same options, as in GENERATED BY DEFAULT AS IDENTITY (START WITH 500).

SERIAL and Other Databases

SERIAL is PostgreSQL's older shorthand for an integer column with a sequence as its default. It still works and appears in many tutorials and existing databases:

SQL▶ Try it
CREATE TABLE notes (
  note_id SERIAL PRIMARY KEY,
  body    TEXT
);
 
INSERT INTO notes (body) VALUES ('Loops quiz'), ('Streams review')
RETURNING *;
Output
CREATE TABLE
 
 note_id |      body
---------+----------------
       1 | Loops quiz
       2 | Streams review
(2 rows)

It behaves like GENERATED BY DEFAULT, but it isn't standard SQL and its sequence is a separate object that's easy to get wrong when copying tables. Use identity columns for new work.

DatabaseAuto-numbered column
PostgreSQL (standard)id INTEGER GENERATED ALWAYS AS IDENTITY
PostgreSQL (older)id SERIAL
MySQLid INT AUTO_INCREMENT
SQL Serverid INT IDENTITY(1,1)
Oracle 12c and laterid NUMBER GENERATED ALWAYS AS IDENTITY
SQLiteid INTEGER PRIMARY KEY (numbered automatically)
Accessid AUTOINCREMENT

Tabs showing each database's version are coming to this course.

IDENTITY, SERIAL, AUTO_INCREMENT and IDENTITY(1,1), and how each returns the new id

Common Mistakes

Finding the new id with max(id). Two inserts at once get the same answer. Use RETURNING.

Typing ids by hand into a BY DEFAULT column. The counter later hands out the same number and the insert fails. Use GENERATED ALWAYS.

Expecting no gaps. Failed inserts, rollbacks and deletes all leave gaps.

Using ids as a count of rows. The highest id says nothing about how many rows exist. Use count(*).

Interview Corner

How do you create an auto-incrementing primary key in PostgreSQL?

id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, the SQL-standard identity column. The older SERIAL also works. MySQL uses AUTO_INCREMENT, and SQL Server uses IDENTITY(1,1).

Why can there be gaps in an identity column?

Numbers come from a sequence and are never reused, even if the insert fails or is rolled back. That lets concurrent inserts proceed without waiting for each other.

How do you get the id of a row you just inserted?

In PostgreSQL, INSERT ... RETURNING id. In MySQL, LAST_INSERT_ID(); in SQL Server, SCOPE_IDENTITY() or OUTPUT. Never max(id).

Practice

Challenge: Create a table practice_goals with a goal_id that the database always generates, a required student_id and a required goal of up to 80 characters. Insert two goals in one statement, one for Navika (103), "Finish JavaScript Basics", and one for Advitha (102), "Review Java OOP", and get back both new ids with their goals.

Show solution
SQL▶ Try it
CREATE TABLE practice_goals (
  goal_id    INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  student_id INTEGER NOT NULL,
  goal       VARCHAR(80) NOT NULL
);
 
INSERT INTO practice_goals (student_id, goal)
VALUES (103, 'Finish JavaScript Basics'),
       (102, 'Review Java OOP')
RETURNING goal_id, goal;
Output
CREATE TABLE
 
 goal_id |           goal
---------+--------------------------
       1 | Finish JavaScript Basics
       2 | Review Java OOP
(2 rows)

Two ids, 1 and 2, handed back by the same statement that created them.

Quick check: Auto-increment and identity

3 questions
1session_id is GENERATED ALWAYS AS IDENTITY. What happens if you insert session_id = 10 directly?
2How should a program learn the id of a payment it just inserted?
3An INSERT that took ids 2 and 3 failed. What id does the next successful insert get?

Key Takeaways

You want toWrite
A numbered keyid INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
Start at 500GENERATED BY DEFAULT AS IDENTITY (START WITH 500)
Get the new idINSERT ... RETURNING id
A standalone counterCREATE SEQUENCE receipt_numbers START WITH 1000;
The next numbernextval('receipt_numbers')

Was this tutorial helpful?

Lesson 34 of 115