Interview Q&A · SQL · 12 questions in this topic

Constraints & Keys — SQL Interview Q&A

All SQL topics

Data that cannot lie — primary/foreign keys, uniqueness, checks, defaults and cascading actions. Part of Constraints & Keys · 192 questions in the SQL bank.

What is a primary key?

Answer

A primary key uniquely identifies each row: UNIQUE plus NOT NULL, one per table, the target of foreign keys. Natural keys (email, SSN) vs surrogate keys (auto-increment/BIGSERIAL, UUID) is the design debate — surrogates win on stability (business values change; ids should not).

Every table wants one: keyless tables cannot be reliably updated, joined or replicated.

Example

Example.sqlsql
CREATE TABLE employees (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email CITEXT UNIQUE NOT NULL
);

💡 Unique-plus-not-null-plus-singularity is the definition; surrogate-vs-natural is the judgment.

What is a foreign key and what does it enforce?

Answer

A foreign key constrains a column to values present in another table's key — referential integrity. It blocks orphans on insert/update, and governs deletes via actions (CASCADE, SET NULL, RESTRICT, NO ACTION). Unindexed foreign keys slow parent writes and deletes.

Constraints are the database refusing to store lies — enforce relationships here, not just in application code.

Example

Example.sqlsql
CREATE TABLE orders (
  id BIGINT PRIMARY KEY,
  customer_id BIGINT NOT NULL
    REFERENCES customers (id) ON DELETE RESTRICT
);

What do ON DELETE CASCADE / SET NULL / RESTRICT each do?

Answer

CASCADE deletes children with the parent (convenient, dangerous — one delete fans out). SET NULL orphans safely (child survives, FK nulled — column must be nullable). RESTRICT/NO ACTION block the parent delete while children exist (safest default; RESTRICT checks immediately, NO ACTION at statement end).

Default RESTRICT; choose CASCADE only for genuinely owned children (order lines, never users).

Key points

  1. 1CASCADE — children die with parent.
  2. 2SET NULL — children survive, unlinked.
  3. 3RESTRICT — delete blocked while children exist.

Example

Example.sqlsql
-- order lines die with their order:
FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits