Primary Keys & Auto-Increment / Serial / Identity Columns
Choose primary keys and generate surrogate IDs with SERIAL, IDENTITY, or UUID.
In plain words
A primary key is the unique ID of a row. The database can create these IDs for you automatically.
Think of it like…
A roll number at school: names can repeat and change, but each student gets a number that's unique and never reused, and every record about them uses that number.
Where you’ve seen it
CREATE TABLE orders (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id bigint NOT NULL, …);: the database assigns 1, 2, 3 … and other tables refer to orders by id, even if the order's other details change.
Words you’ll hear
- Primary key
- Unique, NOT NULL, one per table; automatically indexed.
- Surrogate key
- A meaningless generated id (identity, sequence, UUID).
- Natural key
- A real-world unique value (email, ISBN); still worth a UNIQUE constraint.
- Identity column
- SQL-standard auto-generated id: GENERATED … AS IDENTITY (PostgreSQL 10+).
Visual diagram
Theory & example queries
Natural vs surrogate keys
A natural key comes from the data itself: an email, a PAN number, an ISBN. It looks convenient, but real-world values change (people change email), get entered wrongly, or turn out not to be unique. Changing a primary key means updating every foreign key that points at it.
A surrogate key has no meaning, so it never needs to change. The usual design is a surrogate primary key plus a UNIQUE constraint on the natural key, which gives you stable references and still prevents duplicates.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
CREATE TABLE users ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL UNIQUE, name text);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative command response
Note: The table is created only if the name is available and the statement runs under PostgreSQL-compatible identity syntax.
Key takeaway: Use a surrogate primary key, and enforce natural uniqueness with UNIQUE.
Identity, auto-increment or UUID?
Sequential integers (PostgreSQL IDENTITY or the older SERIAL, MySQL AUTO_INCREMENT, SQL Server IDENTITY) are small and insert in order, which keeps the index compact. Use bigint: int tops out around 2.1 billion. Expect gaps, because failed or rolled-back inserts consume values. Sequential ids also reveal how many records you have if they appear in URLs.
UUIDs can be generated by the application or on other servers without coordination, and don't leak counts. Random UUIDv4 values scatter inserts across the index, which hurts performance on big tables; time-ordered UUIDv7 keeps inserts sequential (PostgreSQL 18 has a built-in uuidv7()). They take 16 bytes versus 8 for bigint.
| id | created_at | archived |
|---|---|---|
| 1 | 2024-11-20 | false |
| 2 | 2024-12-15 | false |
| 3 | 2026-01-05 | false |
CREATE TABLE events ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), …);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative command response
Note: This assumes the remaining columns replace the ellipsis, the events table does not exist, and the selected UUID function is available in the PostgreSQL version.
(or DEFAULT uuidv7() on PostgreSQL 18 for time-ordered ids).
Key takeaway: bigint identity by default; UUIDv7 when ids are generated outside the database or must not be guessable.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide what identifies a row
Find the real-world uniqueness rule (one user per email) and decide whether it's stable enough to be the key. Usually it isn't.
email is unique, but can change
When to use it & trade-offs
What it is
A primary key uniquely identifies each row: it must be unique and NOT NULL, and a table has at most one. Most tables use a surrogate key, an id generated by the database (an identity or auto-increment column, or a UUID), rather than a natural key such as an email address.
Why it matters: Every join, foreign key and update depends on reliably identifying rows. Picking the key type affects storage, insert speed, how ids look in URLs, and whether you can generate ids outside the database. Interviewers often ask "natural or surrogate?" and "int or UUID?".
When to reach for it
- Every table gets a primary key
- bigint identity columns for ordinary application tables
- UUIDs when ids are generated outside the database or exposed publicly
When to avoid or be careful
- Using an email or phone number as the primary key
- int ids on tables that might grow past 2 billion rows
- Expecting sequence values to be gap-free (don't use them as invoice numbers)
bigint identity vs UUIDv4 vs UUIDv7
Strengths: 8 bytes, ordered inserts, compact indexes, easy to read.
Watch out: Generated only by the database; sequential ids are guessable in URLs.
Strengths: No coordination needed; not guessable.
Watch out: 16 bytes; random inserts fragment the index and slow down large tables.
Strengths: No coordination, and inserts stay roughly in order.
Watch out: 16 bytes; leaks the approximate creation time.
Interview signals & numbers to know
When this topic comes up
- “Natural vs surrogate key?”
- “Auto-increment or UUID?”
- “Why are there gaps in my ids?”
- Integer overflow on an id column
- Distributed id generation
Benchmarks & rules of thumb
- 2,147,483,647
- maximum int value
- 8 bytes
- bigint key
- 16 bytes
- UUID key
Common mistakes & follow-ups
Common interview mistakes
- Choosing a natural key that later changes, forcing updates to every referencing row.
- Using int for ids and hitting overflow years later on a busy table.
- Treating id gaps as data loss or using sequence numbers where gap-free numbering is a legal requirement.
Likely interviewer follow-ups
- What are the trade-offs between auto-increment ids and UUIDs?
- Why do identity columns have gaps, and when is that a problem?
- What's the difference between a primary key and a unique constraint?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Primary Keys & Auto-Increment / Serial / Identity Columns with hands-on SQL practice and interview Q&A.