Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 8/ 160
01. SQL Foundations & Relational Concepts

Primary Keys & Auto-Increment / Serial / Identity Columns

Choose primary keys and generate surrogate IDs with SERIAL, IDENTITY, or UUID.

BeginnerPK · SERIAL · UUID3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Surrogate PK plus a unique natural keyQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE TABLE users (2  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3  email text NOT NULL UNIQUE,4  name text5);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command response
CREATE TABLE

Note: The table is created only if the name is available and the statement runs under PostgreSQL-compatible identity syntax.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

A UUID key in PostgreSQLQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE TABLE events (2  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),3  …);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command response
CREATE TABLE

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

(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.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

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.

Focus at this step

email is unique, but can change

What to watch at this step
Natural key
keep as UNIQUE
Tip: use ← → to move between steps

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

bigint identity / auto-increment
Best for: Most application tables

Strengths: 8 bytes, ordered inserts, compact indexes, easy to read.

Watch out: Generated only by the database; sequential ids are guessable in URLs.

UUIDv4 (random)
Best for: Ids created by clients or several services

Strengths: No coordination needed; not guessable.

Watch out: 16 bytes; random inserts fragment the index and slow down large tables.

UUIDv7 (time-ordered)
Best for: Distributed id generation on 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?
Interview tip: Give the default (bigint identity primary key, natural key as UNIQUE), then explain when you'd switch to UUIDs. Mentioning UUIDv7 and index locality shows production experience.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Creating & Dropping Databases and Tables (CREATE, DROP, ALTER)
Next topic
Foreign Keys & Referential Integrity (ON DELETE CASCADE, SET NULL)