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

Schema Design & Security — SQL Interview Q&A

All SQL topics

Senior-level design — normalization trade-offs, key strategies, migrations and SQL injection defense. Part of Design & Security · 192 questions in the SQL bank.

How do you design a schema from scratch (orders example)?

Answer

Identify entities (customers, orders, lines, products), give each a surrogate key, relate via foreign keys, normalize to 3NF, add constraints (NOT NULL, CHECK, UNIQUE), index access paths, and seed with representative data for EXPLAIN testing.

Entities, keys, relations, constraints, indexes — the design march in order.

Key points

  1. 1Entities + surrogate keys.
  2. 2Relations via foreign keys.
  3. 3Constraints, then indexes.

Example

Example.sqlsql
CREATE TABLE orders (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES customers (id),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

💡 Walk entities-to-indexes in order — interviewers grade the sequence.

When do you denormalize, and what does it cost?

Answer

Denormalize for proven read hotspots: counters, rollup columns, star-schema dimensions —Trading write complexity (sync logic, triggers, jobs) for read speed. Costs: storage duplication, update anomalies, sync bugs. Mitigate with single-writer paths, reconciliation jobs, and comments documenting the redundancy contract.

Measure first, duplicate deliberately, reconcile always.

Key points

  1. 1Why — proven read hotspots only.
  2. 2Cost — sync logic and anomaly risk.
  3. 3Guard — single writer plus reconciliation.

Surrogate vs natural vs UUID keys — how do you choose?

Answer

Surrogate integers (IDENTITY/SERIAL): compact, fast, meaningless — the default. Natural keys: meaningful but mutable (emails change). UUIDs: globally unique, merge-safe, larger and random-IO heavy (v7/ordered variants mitigate).

Default integer surrogate; UUIDs for distributed/merge-heavy systems; natural keys behind UNIQUE, never as PK.

Key points

  1. 1Integer surrogate — compact default.
  2. 2UUID — distributed merge-safety, larger.
  3. 3Natural — UNIQUE constraint, not PK.

Example

Example.sqlsql
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),  -- distributed-safe
-- vs: id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY

💡 Meaningless-and-stable wins PK; meaningful gets UNIQUE.

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