// free study notes

SQL schema design & normalization interview questions

Design questions have no single right answer, which is exactly why interviewers ask them. Each answer gives the standard solution and its tradeoffs.

12 questions
  • 2 easy
  • 8 medium
  • 2 hard
Practice mode: all topics, shuffled

What this page covers

  • 12 questions on schema design & normalization, tagged easy, medium or hard, each with a worked answer in runnable SQL.
  • One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
  • Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
The shop schema
customers(customer_id, name, city, signup_date)
orders(order_id, customer_id, order_date, status, total)
order_items(order_id, product_id, quantity, unit_price)
products(product_id, name, category, price)
employees(employee_id, name, manager_id, department, salary, hired_on)

The questions

What is first normal form (1NF)?

Easy

Every column holds a single atomic value, and rows are unique. No comma-separated lists in a cell, no repeating column groups like phone1, phone2, phone3.

-- Violates 1NF:
orders(order_id, product_names TEXT)  -- "widget, gadget, sprocket"

-- In 1NF:
orders(order_id, ...)
order_items(order_id, product_id, quantity)

The reason it matters beyond theory: a comma-separated list cannot be joined, indexed or constrained, and every query that needs one product must parse text. The repeating-columns version cannot be extended without ALTER TABLE. The fix is a child table, which is also the answer to the many-to-many question.

Explain second and third normal form with a concrete example.

중간

2NF: every non-key column depends on the whole key, not part of it. 3NF: every non-key column depends on the key and nothing else, so no non-key column determines another one. One example of each:

-- Violates 2NF: key is (order_id, product_id)
order_items(order_id, product_id, quantity,
product_name)          -- depends on product_id alone, part of the key

-- Violates 3NF: key is order_id
orders(order_id, customer_id,
customer_city)         -- depends on customer_id, a non-key column
-- Decomposed:
products(product_id, product_name)
orders(order_id, customer_id)
customers(customer_id, city)
order_items(order_id, product_id, quantity)

2NF can only be violated when the key is composite; 3NF removes transitive dependencies (order_id determines customer_id, which determines city). The damage is the same in both cases: one fact is stored in many rows, so renaming a product or moving a customer means updating all of them, and missing one leaves the rows disagreeing.

Surrogate keys or natural keys: how do you choose?

Easy

A surrogate key has no business meaning (an identity or sequence bigint, or a UUID); a natural key comes from the data itself (email, ISBN, country code). The practical rule: surrogate primary key for stability, UNIQUE constraint on the natural key for correctness.

CREATE TABLE users (
user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email   VARCHAR(320) NOT NULL UNIQUE      -- natural key, still enforced
);

The reasons for surrogates: business keys change (an email update would cascade through every FK), they are narrow (a 4-byte or 8-byte FK beats a 320-character one in every child index), and nothing real is guaranteed immutable. The reason to keep the natural key as UNIQUE: without it, the surrogate hides duplicate real rows.

How do you model a many-to-many relationship?

중간

A junction (bridge) table holding both primary keys, usually with a composite key of the pair, and foreign keys to both sides.

CREATE TABLE order_items (
order_id    BIGINT REFERENCES orders(order_id),
product_id  BIGINT REFERENCES products(product_id),
quantity    INT NOT NULL,
unit_price  NUMERIC(10,2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);

The follow-up: relationship attributes such as quantity belong on the junction row, not on either endpoint. If the same product can appear on two lines of one order (say, at different prices), the composite key is too strict and you need a line number in the key or a surrogate key. A rule like every order must have at least one item cannot be expressed with foreign keys alone; it needs application logic, a trigger or a deferred check.

How do you model an employee manager relationship in the same table?

중간

A self-referencing foreign key: manager_id points at the same table's primary key, nullable for the top of the hierarchy.

CREATE TABLE employees (
employee_id BIGINT PRIMARY KEY,
name        VARCHAR(200) NOT NULL,
manager_id  BIGINT REFERENCES employees(employee_id)   -- NULL = CEO
);

The follow-ups to expect: reading the whole chain needs a recursive CTE; deleting a manager who has reports is either blocked (the default) or, with ON DELETE SET NULL, leaves the reports without a manager, so reassigning them belongs in the delete path; and cycles. A CHECK (manager_id <> employee_id) blocks the one-step loop of an employee managing themselves, but A manages B, B manages A passes every constraint; catching that needs a trigger or application check that walks the chain before the update.

When is denormalization justified?

중간

When reads dominate writes and the join or aggregation cost is measurable: reporting tables, dashboards, counters, and data spread across services. Denormalization trades update-anomaly risk for read speed, so it must come with a maintenance path.

-- Normalized source of truth:
orders(order_id, customer_id, total, ...)

-- Denormalized read model:
customer_stats(customer_id, order_count, lifetime_value)  -- refreshed on write or on schedule

The disciplined answer: normalize first, denormalize specific paths after measuring, and state the sync strategy (trigger, transactional outbox, or scheduled rebuild) plus the staleness tolerance. Denormalizing up front adds sync code before anyone knows which reads are slow; refusing to denormalize while a dashboard aggregates 500M rows on every page load is the opposite mistake.

How would you store hierarchical data? Compare adjacency list, nested sets and closure table.

Hard

Adjacency list (each row points at its parent) is simple and cheap to write; reading a whole subtree needs a recursive CTE, which every modern engine has. Nested sets (each node stores left and right bounds) reads whole subtrees in one query but makes every insert or move rewrite half the table. A closure table (one row per ancestor-descendant pair) answers subtree and ancestor queries with a plain join, and inserting a leaf is cheap, at the cost of one row per ancestor for every node; moving a subtree means deleting and reinserting many path rows.

-- Adjacency list: the default choice today
categories(category_id, name, parent_id REFERENCES categories)

-- Closure table: fast subtree queries at any depth
category_paths(ancestor_id, descendant_id, depth)

The senior answer starts with an adjacency list plus recursive CTEs and reaches for the others only when measurements say so: nested sets for trees that almost never change, a closure table when subtree queries are the hot path and moves are rare. The fourth option is a materialized path, storing the lineage as text such as '/1/7/42/', which makes subtree queries a prefix LIKE; PostgreSQL's ltree type and SQL Server's hierarchyid are built-in versions of it.

When should a column be NULLable, and what are the tradeoffs?

중간

NULL means unknown or not applicable, and every NULLable column spreads three-valued logic through every query that touches it. Make a column NOT NULL by default and nullable only when absence is a real state of the world.

CREATE TABLE customers (
email           VARCHAR(320) NOT NULL,        -- every customer has one
middle_name     VARCHAR(200),                 -- genuinely optional
deleted_at      TIMESTAMPTZ                   -- NULL = not deleted (soft delete)
);

The costs to name: NULL defeats = comparisons, breaks NOT IN, needs COALESCE or IS NOT NULL everywhere, and makes aggregates silently skip rows. When NULL could mean two different things (not yet known versus not applicable), use a separate column or a status value so the meaning is explicit. Defaulting every optional field to empty string is the opposite mistake, since empty string and unknown become indistinguishable.

How do you model a one-to-one relationship?

중간

Put the foreign key on the optional side with a UNIQUE constraint, or split a wide table when a subset of columns is rarely read or has different access permissions.

CREATE TABLE users (
user_id     BIGINT PRIMARY KEY,
email       VARCHAR(320) NOT NULL
);

-- At most one profile per user: user_id is both the PK and the FK
CREATE TABLE user_profiles (
user_id     BIGINT PRIMARY KEY REFERENCES users(user_id),
bio         TEXT,
avatar_url  VARCHAR(500)
);

The reasons to split: the profile columns are large, read rarely, or need different permissions. Making the child's primary key also its foreign key allows at most one profile per user; a separate profile_id key plus a UNIQUE constraint on user_id says the same thing. Strictly this is one-to-zero-or-one: forcing every user to have a profile needs a deferred constraint or application logic, since one of the two rows has to be inserted first.

How do you store data that changes over time (temporal / versioned data)?

Hard

Validity ranges: add valid_from and valid_to to the rows that represent history, with an open end for the current row, and on PostgreSQL enforce non-overlap with an exclusion constraint.

-- PostgreSQL; btree_gist lets the GiST index handle product_id WITH =
CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE product_prices (
product_id BIGINT REFERENCES products(product_id),
price      NUMERIC(10,2) NOT NULL,
valid_from TIMESTAMPTZ NOT NULL,
valid_to   TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
CONSTRAINT no_overlap EXCLUDE USING gist (
product_id WITH =, tstzrange(valid_from, valid_to) WITH &&
)
);

-- Price of a product as it was on a given date:
SELECT price FROM product_prices
WHERE product_id = 42
AND '2025-03-15' >= valid_from AND '2025-03-15' < valid_to;

The discipline: half-open ranges [from, to) so one row's end can equal the next row's start without overlapping; a current-price view filters valid_to = 'infinity'; and a price change never overwrites, it closes the old row and inserts a new one in one transaction. PostgreSQL 18 can declare the same rule as a temporal key, PRIMARY KEY (product_id, valid_period WITHOUT OVERLAPS) on a range column. On engines without either, overlap prevention moves to triggers or serialized transactions. Also worth naming: SQL:2011 system-versioned tables (SQL Server 2016+, MariaDB 10.3+), where the engine records every row's history automatically. They track when the database knew a fact, which is a different question from when a price was valid.

What is the EAV pattern, and why is it dangerous?

중간

Entity-attribute-value stores the schema as data: instead of one column per attribute, every attribute becomes a row of (entity_id, attribute, value). Users can add fields without a schema change, and almost everything else gets harder.

-- EAV:
entity_values(entity_id, attribute, value)
-- (42, 'price', '19.99'): a number stored as text, cast back on every read

-- Versus typed columns:
products(product_id, price NUMERIC, weight_kg NUMERIC, color VARCHAR)

The costs to enumerate: no column types or constraints (everything is TEXT), every query is a pivot or a chain of self-joins, the planner has no statistics per attribute, and NOT NULL or FK rules are unenforceable. When user-defined attributes are a genuine requirement, JSONB (PostgreSQL) or JSON columns with generated columns and indexes over the hot attributes give the flexibility with types attached. EAV survives in clinical and CMS systems where the attribute set is open-ended and defined by users; even there, the cost shows up in every report.

How much integrity should live in the schema versus the application?

중간

Push what the engine can enforce into the schema: primary keys, foreign keys, UNIQUE, NOT NULL, CHECK and (where supported) exclusion constraints. The engine enforces them for every writer and every transaction; application code enforces them only on the paths where someone remembered to.

CREATE TABLE order_items (
order_id   BIGINT NOT NULL REFERENCES orders(order_id),
product_id BIGINT NOT NULL REFERENCES products(product_id),
quantity   INT    NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(10,2) NOT NULL CHECK (unit_price >= 0),
PRIMARY KEY (order_id, product_id)
);

What belongs in the application: cross-table business rules the schema cannot express (an order limit per customer tier), user-facing validation with good error messages, and anything needing external systems. The point that lands well: batch jobs, migrations, a second service and someone's manual UPDATE all bypass your application code, but none of them bypass the constraint. Application checks also race: two requests can both check that an email is free and both insert it, and only a UNIQUE constraint stops the second one. Checking in both layers is normal, the application for friendly error messages and the schema for the guarantee.

Schema design & normalization interview FAQ

Which normal forms do these questions cover?

First, second and third normal form, each with a concrete table that violates the form and the decomposition that fixes it, plus when breaking 3NF is the right call.

Is there a question about modeling many-to-many relationships?

Yes: the junction-table pattern with a composite key, and the follow-up about putting extra columns such as quantity on the junction row.

Do the answers take sides on surrogate versus natural keys?

They explain both, then give the rule most teams settle on: a surrogate primary key for stability, plus a UNIQUE constraint so the natural key still cannot repeat.

Are there system-design style questions?

Yes: storing hierarchies three ways, temporal data with valid_from and valid_to, audit history, and the EAV pattern with the reasons it goes wrong.

Other topics

// from study notes to daily tool

Now write some SQL against a real database

SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your schema, a formatter, guardrails for risky queries, and every engine in one app.