Skip to content
Learn Netverks

Lesson

Step 13/36 36% through track

primary-keys

Primary keys

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~2 min
Level
beginner

This lesson

This lesson teaches Primary keys: the SQL patterns, schema habits, and query reasoning you need before advancing in SQL.

Keys enforce referential integrity—ORMs hide them until migrations fail in production.

You will apply Primary keys in contexts like: Postgres, MySQL, SQLite, warehouses, and ORMs that still expose SQL.

Copy SQL from each lesson into SQLite (sqlite3), DB Fiddle, or local Postgres—read result grids and row counts. The in-browser SQL lab (sql_sandbox) will run queries when the runner ships; until then, local clients are the practice path.

When you can explain the previous lesson's ideas without copying example queries verbatim.

A primary key uniquely identifies each row. Single-column integer keys are common; composite keys appear when natural business identifiers combine (order_id + line_no).

Single-column key

CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  username TEXT NOT NULL UNIQUE
);

INSERT INTO users (username) VALUES ('ada');
SELECT last_insert_rowid();  -- SQLite auto-increment helper

Practice: Run DDL in a fresh SQLite file or DB Fiddle schema pane. Drop test tables when experimenting.

Composite primary key

CREATE TABLE order_items (
  order_id INTEGER NOT NULL,
  line_no INTEGER NOT NULL,
  product_id INTEGER NOT NULL,
  qty INTEGER NOT NULL,
  PRIMARY KEY (order_id, line_no)
);

Both columns together must be unique; either alone may repeat.

Natural vs surrogate keys

Surrogate keys (auto id) stay stable when business data changes. Natural keys (email, ISBN) encode domain meaning but may change or collide—teams often still add surrogate ids.

Important interview questions and answers

  1. Q: Can a table have two primary keys?
    A: No—one primary key constraint, which may span multiple columns.
  2. Q: UNIQUE vs PRIMARY KEY?
    A: Both enforce uniqueness; PRIMARY KEY implies NOT NULL and is the main row identifier.

Self-check

  1. When is a composite primary key appropriate?
  2. Why do ORMs often prefer surrogate integer ids?

Tip: Surrogate integer keys simplify ORMs; natural keys still get UNIQUE constraints when needed.

Interview prep

Composite PK?

Multiple columns together uniquely identify a row.

Surrogate key?

Meaningless stable id (often integer) separate from business data.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Surrogate vs natural?
  • Composite PK?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump