Interview Q&A · SQL · 12 questions in this topic
Constraints & Keys — SQL Interview Q&A
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
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
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
- 1CASCADE — children die with parent.
- 2SET NULL — children survive, unlinked.
- 3RESTRICT — delete blocked while children exist.
Example
-- order lines die with their order: FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE
What is the difference between UNIQUE, PRIMARY KEY and an index?
Answer
PRIMARY KEY is the table's identity (unique, not null, one). UNIQUE enforces distinctness on other columns (allowing NULLs, mostly). An index is a performance structure that may or may not enforce anything — unique constraints are implemented via unique indexes, but plain indexes constrain nothing.
Constraint (rule) vs index (mechanism) is the conceptual split.
Example
email CITEXT UNIQUE NOT NULL, -- constraint (rule) CREATE INDEX idx_emp_dept ON employees (department); -- index (speed)
How do UNIQUE constraints treat NULLs?
Answer
In standard SQL (and PostgreSQL), NULLs are distinct from each other — multiple NULLs allowed in a UNIQUE column. SQL Server (historically) and some engines allow only one. Partial unique indexes (WHERE deleted_at IS NULL) scope uniqueness to live rows — the soft-delete answer.
This NULL-distinctness is why UNIQUE cannot stand in for a primary key.
Example
-- uniqueness among live rows only (PostgreSQL): CREATE UNIQUE INDEX ux_users_email ON users (email) WHERE deleted_at IS NULL;
💡 NULLs-are-distinct plus partial-indexes-for-soft-delete is the complete NULL-uniqueness answer.
What are CHECK constraints? What are their limits?
Answer
CHECK enforces row-level predicates (salary >= 0, end > start) — rejected writes fail fast with clear errors. Limits: no subqueries or cross-table references (use triggers or deferred constraints), NULL passes (UNKNOWN is not FALSE — pair with NOT NULL), and complex rules belong in application validation plus the constraint as backstop.
CHECK is the cheapest invariant enforcement available — use it for every column-local rule.
Example
salary NUMERIC(12,2) CHECK (salary >= 0), CONSTRAINT valid_range CHECK (end_time > start_time)
What are NOT NULL and DEFAULT?
Answer
NOT NULL bans missing values — the nullability decision per column (required facts: ids, names, amounts). DEFAULT supplies values for omitted inserts (0, '', now(), generated expressions) so writers need not repeat constants.
Nullable-by-default (SQL Server/PostgreSQL) means every column is a NULL decision you must make deliberately.
Example
name VARCHAR(100) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), bonus NUMERIC(12,2) DEFAULT 0
💡 Every column deserves an explicit NULL verdict — implicit nullability is how mystery NULLs breed.
What is the difference between `UNIQUE` and `PRIMARY KEY` with NULLs, and composite keys?
Answer
PRIMARY KEY forbids NULLs entirely and exists once; UNIQUE permits (mostly multiple) NULLs and repeats across columns. Composite keys (PRIMARY KEY (a, b)) identify by combination — join tables, line items, effective-dated rows.
Composite natural keys are honest modeling; surrogate plus UNIQUE on the natural combo is the pragmatic hybrid.
Example
PRIMARY KEY (order_id, line_no), -- composite: the pair identifies UNIQUE (tenant_id, email) -- scoped uniqueness
How do you enforce conditional uniqueness (only active rows unique)?
Answer
Partial unique indexes (WHERE predicate) scope enforcement to matching rows — active emails unique, archived duplicates allowed. Functional unique indexes (LOWER(email)) normalize before comparing. Both beat triggers for clarity and concurrency.
Conditional rules want partial indexes; normalized rules want expression indexes.
Example
CREATE UNIQUE INDEX ux_active_email ON users (LOWER(email)) WHERE deleted_at IS NULL;
💡 Partial for conditions, expression for normalization — the two specialized-uniqueness tools.
How do deferrable constraints work (DEFERRABLE INITIALLY DEFERRED)?
Answer
Deferrable constraints check at COMMIT instead of per-statement — enabling cyclic inserts (A references B, B references A) and multi-statement reorders within one transaction. SET CONSTRAINTS toggles timing per transaction. Non-deferrable (the default) checks immediately per row/statement.
Use sparingly: deferred checking delays error discovery to COMMIT, complicating error attribution.
Example
-- PostgreSQL: FOREIGN KEY (manager_id) REFERENCES employees (id) DEFERRABLE INITIALLY DEFERRED
Should constraints live in the database or the application?
Answer
Both, layered: database constraints are the last line of defense (correct under every writer — apps, jobs, consoles, bugs), application validations give friendly errors and rich rules. Constraints alone are cryptic; validations alone are bypassable.
The database refuses lies; the application explains them — state both halves.
Key points
- 1Database — inviolable, writer-independent, terse errors.
- 2Application — expressive, user-friendly, bypassable.
💡 Backstop-vs-explainer is the framing that ends the debate correctly.
How do you add a constraint to a table full of dirty data?
Answer
Profile violations first (queries finding NULLs/dupes/out-of-range), clean or quarantine them, then ADD CONSTRAINT (NOT VALID + VALIDATE separately in PostgreSQL to avoid long locks). Test on a copy; schedule off-peak; keep the cleanup script for the next dirty table.
Constraints on dirty data fail — the cleanup is the migration, the ALTER is the ceremony.
Example
-- PostgreSQL low-lock pattern: -- ALTER TABLE t ADD CONSTRAINT c CHECK (x > 0) NOT VALID; -- ALTER TABLE t VALIDATE CONSTRAINT c;
💡 Clean-then-constrain plus NOT VALID/VALIDATE is the production migration pattern.
Recommended resourcesAffiliate links · may earn us a commission