Skip to content
Tech Interview Prep
Technical interview guide

Schema Design & Normalization

Structuring tables to avoid redundant, inconsistent data, and knowing when to deliberately break the rules for performance.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain normalisation through third normal form with a worked example.

Answer

Normalisation is a formal way of saying "store each fact once". Each normal form removes one way a table can hold the same fact in two places. I'll take one table through 1NF, 2NF and 3NF and show what each step actually removes.

Assume a single relational database, no deliberate denormalisation for read performance, and that we care about update anomalies rather than query speed.

Starting point. An order table where each row carries the customer's details and the items are crammed into one cell:

order_idcustomer_idcustomer_emailcustomer_cityitems
1001C-77ada@example.comLisbon'SKU-1 x2, SKU-9 x1'
1002C-77ada@example.comLisbon'SKU-1 x1'
1003C-91bo@example.comPorto'SKU-9 x3'

1NF: every column holds a single value from its domain; no repeating groups. items breaks it: you cannot index, constrain or join it without string surgery, and a SKU containing a comma corrupts the row. Split to one row per item, key (order_id, sku):

order_idskuqtyunit_price_paidcustomer_idcustomer_emailcustomer_city
1001SKU-1219.99C-77ada@example.comLisbon
1001SKU-914.50C-77ada@example.comLisbon
1002SKU-1119.99C-77ada@example.comLisbon
1003SKU-934.50C-91bo@example.comPorto

2NF: every non-key column depends on the whole key, not part of it. qty and unit_price_paid depend on (order_id, sku). customer_id, customer_email and customer_city depend only on order_id: a partial dependency. Split into orders(order_id, customer_id, customer_email, customer_city) and order_items(order_id, sku, qty, unit_price_paid).

3NF: no non-key column depends on another non-key column. In orders, customer_email and customer_city depend on customer_id, which is not the key. That is a transitive dependency. Split again:

customers(customer_id, email, city), orders(order_id, customer_id), order_items(order_id, sku, qty, unit_price_paid).

What the last step bought. Ada changes her email. Before, that is an UPDATE across every order row she owns: 2 rows in the starting table, 3 after 1NF, 2 in orders after 2NF. After 3NF it is one row in customers. The failure mode is not the extra writes; it is that a partial update leaves C-77 with two different emails and nothing in the schema says which is right. The database is self-contradictory and no constraint catches it.

The trap. unit_price_paid stays on order_items even though products has a price. The price paid is a fact about this order line; the current price is a fact about the product. Moving it would be wrong.

BCNF tightens 3NF: every determinant must be a superkey. It differs only when candidate keys overlap. enrolment(student, subject, teacher) with {student, subject} → teacher and teacher → subject: candidate keys are {student, subject} and {student, teacher}. teacher → subject has a non-superkey determinant, but subject is prime, so 3NF permits it and BCNF does not.

The trade. Normalisation makes update anomalies structurally impossible and costs joins at read time. A join is a performance problem you can measure and fix; inconsistent data is a correctness problem you often cannot detect.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How do you decide between a natural key and a surrogate key?

Answer

My default is a surrogate primary key plus a unique constraint on the natural key, and the 'plus' is the part people drop.

The case for natural keys is that they need no extra column, the uniqueness they enforce is meaningful to the business, and a child row carrying the value is directly useful without a join. The case against is that business identifiers change (people change email addresses, product codes get reissued, countries get renamed) and when a key changes it must cascade through every referencing row. They also tend to be wide, which inflates every index carrying them.

So the surrogate provides stable identity and cheap references; the unique constraint on the natural key preserves the real-world rule. Removing that constraint because 'the id is the primary key' is exactly how a system ends up with two customers sharing an email.

Between sequence and UUID: a sequential integer is compact with good index locality, but it leaks volume, anyone with an id can estimate how many you have, and it is enumerable in a URL. A random UUID fixes both and can be generated client-side without a round trip, which matters for offline-capable or distributed writers. Its costs are width and scattered index inserts, which hurt write locality and cache behaviour on large tables. Time-ordered variants like UUIDv7 recover most of the locality while keeping client generation, and that is where I would start today for anything public-facing.

One worthwhile refinement: the internal primary key and the externally exposed identifier do not have to be the same thing. A compact sequential integer internally with an opaque public identifier alongside it gives good locality and no enumeration, at the cost of one extra indexed column.

The exception to all of this is a junction table, where the composite of the two foreign keys genuinely is the identity, and making it the primary key enforces pair uniqueness for free.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Explain how you would model a many-to-many relationship with attributes.

Answer

A many-to-many relationship needs a third table holding one row per association: students and courses become an enrolments table with student_id and course_id, each a foreign key.

The primary key should be the composite of both columns. That enforces the rule that a student cannot enrol twice in the same course, which is exactly the integrity constraint the design needs, and it provides an index for student-first lookups. I add a separate index on course_id, because a composite key only serves queries leading with its first column: without it, 'everyone in this course' scans.

The moment the relationship has attributes of its own (enrolled_at, grade, role) the junction table is their natural home, and that is a positive reason to model it explicitly rather than hiding it behind an ORM's implicit join table. Those attributes belong to the association, not to either entity, and there is nowhere else they fit correctly.

When attributes appear, the question of a surrogate key comes up. I add one only when something else must reference an individual enrolment (an attendance table pointing at a specific enrolment, say) or when the ORM requires it. If I do add one, I keep the unique constraint on the pair, because otherwise I have just permitted the duplicates the composite key was preventing. That is the most common mistake here: the surrogate arrives and the pair constraint quietly does not.

On deletes: ON DELETE CASCADE from both parents is usually right, since an enrolment has no meaning without both its student and its course. But if the enrolment carries a grade that must survive for transcript purposes, cascade is wrong and the design needs either RESTRICT with an archival step, or a separate immutable record, which is worth asking about rather than defaulting.

Querying is a two-hop join, with the usual cautions: filtering the far side of a LEFT JOIN belongs in ON if unmatched rows must survive, and any aggregate over the joined result is subject to fan-out.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Which integrity rules belong in the database, and which can live in the application?

Answer

The dividing line is whether the rule must hold regardless of who is writing. The database is the one component every writer passes through: the application, migrations, background jobs, admin consoles, and someone at a psql prompt during an incident. Application validation is a usability feature that produces good error messages; it is not a guarantee, because the next writer may not run that code.

So the schema gets: NOT NULL for required values; PRIMARY KEY for identity; UNIQUE for real-world uniqueness; FOREIGN KEY for relationships with a deliberately chosen ON DELETE action; CHECK for row-level invariants like a non-negative quantity or an end date at or after a start; partial unique indexes for 'one active per user'; and exclusion constraints for non-overlapping ranges.

That last group matters more than it looks, because those are precisely the rules people try to enforce with a query before an insert, and check-then-insert is a race. Two concurrent transactions both see no conflict and both write; under snapshot isolation neither sees the other's uncommitted row. Only the constraint is atomic. Any rule implemented as 'SELECT to check, then INSERT' is broken under concurrency, and it will pass every test because tests are sequential.

The application keeps: format and presentation validation, cross-system rules the database cannot see, anything requiring an external call, complex workflow rules that change frequently, and friendly error messages. It should also duplicate the schema rules for a good user experience, failing fast with a clear message rather than surfacing a constraint violation, but as a convenience layered on top of the guarantee, not instead of it.

The genuine limits: cross-row and cross-table invariants often cannot be expressed declaratively and need a trigger, a different constraint type, or serialisable isolation. And adding a constraint to a large live table needs a NOT VALID-then-validate migration to avoid a long lock. Neither is a reason to move the guarantee into application code.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

What is the difference between a schema that permits a bug and one that prevents it?

Answer

A schema defines the set of states the system can reach. Every constraint removes states from that set permanently. So the question I ask of any design is not 'does this store what we need', almost any design does, but 'what invalid states does this still permit', because over a long enough period, the reachable invalid states will be reached.

A concrete pair. A schema with status text and a comment listing the valid values permits 'shiped', 'SHIPPED', 'Shipped ' and NULL. Every consumer must then defend against all of them, and eventually one will not. A schema with status text NOT NULL CHECK (status IN (...)) makes those states unreachable, and every consumer can rely on it without checking.

The distinction is that the first documents an intention and the second enforces it, and only the second survives contact with a writer who did not read the documentation: a migration, a data fix, a new service, a contractor.

The stronger version of the idea is designing so the invalid state cannot be expressed. Currency at order level rather than line level does not merely discourage mixed-currency orders, it makes them unrepresentable. A composite primary key on a junction table does not detect duplicate enrolments, it makes them impossible. That is strictly better than a constraint that rejects, because there is nothing to reject.

The honest limits: not every invariant is expressible declaratively, cross-row and cross-table rules often need triggers or serialisable isolation, and over-constraining causes real pain when the business legitimately changes. A constraint encoding a rule that turns out to be a preference becomes an obstacle. So the judgement is which rules are genuinely invariant versus currently true, and I would rather be slightly conservative there than have every business change require a migration.

But the default should be enforcement. The cost of a constraint that later needs relaxing is one migration. The cost of an absent constraint is data you cannot trust, discovered at the worst time, with no way to reconstruct what the invalid rows meant.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

What would make you choose a lookup table over a boolean flag?

Answer

A boolean is right when the state is genuinely binary and will stay binary: is_email_verified is a fair example, and even that one sometimes grows a 'pending' state.

The pressure that makes me reconsider is when I notice booleans accumulating. is_active, is_archived, is_suspended, is_deleted on one table encode a state machine badly: they permit combinations that are meaningless (archived and active at once, suspended and deleted) and every reader must know which combinations are real. Four booleans describe sixteen states of which perhaps four are valid, and nothing prevents the other twelve.

A single status column with a constraint or a lookup table makes the invalid combinations unrepresentable, which is strictly better than documenting them. That is usually the moment to convert.

I also prefer a lookup table when the state needs to carry anything: a display label, a sort order for the UI, an active flag so an option can be retired without rewriting history, a description. A boolean cannot carry those and a check constraint cannot either, so the need arrives as a second table anyway: better to start there.

And when the state must be referenced by other data (a rule table keyed by status, or permissions per state) a foreign key target is required, so a lookup table is the only option.

The practical warning sign I have learnt to act on: the second boolean. One is usually fine. The moment a second lands on the same table describing the same underlying concept, it is worth asking whether these are really two independent facts or one state with several values, because converting later means a migration, a backfill, and updating every query that reads the flags, and by then there are more of them.

The counter-consideration is that booleans are simpler to read and query, and converting a genuinely binary flag into a lookup table for symmetry adds a join for nothing. So the test is whether the states are independent facts or values of one concept.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

A team wants to add a status column with a fixed set of values. Walk through the options.

Answer

The 90-second answer. Ask three things before choosing: will the set change without a deploy, does each value need attributes, and does anything else reference it. Stable, small, constraint-only → a CHECK. Changes, or carries attributes → a lookup table. A native enum only when the set is fixed for the life of the schema.

CHECK constraint. status text NOT NULL CHECK (status IN ('pending','paid','shipped','cancelled')). The values live in the schema, so \d orders documents them and the database rejects anything else. Widening it is a migration, but a cheap one:

SQL
ALTER TABLE orders ADD CONSTRAINT orders_status_check
  CHECK (status IN ('pending','paid','shipped','cancelled','refunded')) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_status_check;

The ADD takes ACCESS EXCLUSIVE but does no scan; VALIDATE takes SHARE UPDATE EXCLUSIVE and scans, and because every existing row already satisfies the wider set, that scan is a read. Two statements instead of one so the exclusive lock is held for milliseconds rather than for the length of the scan. (Postgres. MySQL only began enforcing CHECK in 8.0.16: before that it parsed and discarded it, so a MySQL 5.7 "check" is documentation, not enforcement.)

Native enum. CREATE TYPE order_status AS ENUM (...). Stored as a 4-byte OID, so a long label costs the same as a short one: the opposite of text, where 'cancelled' is 10 bytes. Adding a value is ALTER TYPE ... ADD VALUE (Postgres 12+ permits it inside a transaction, but the new value cannot be used in that same transaction). Removing a value is not supported: you create a replacement type, ALTER TABLE ... ALTER COLUMN status TYPE new_type USING status::text::new_type, then drop the old. Reordering is worse: enums sort by declaration order, so ORDER BY status is neither alphabetical nor the order a UI wants. MySQL's ENUM is a different animal: stored as an integer index, so appending a value at the end can be done in place while inserting one in the middle rebuilds the table.

Lookup table.

SQL
CREATE TABLE order_status (
  code text PRIMARY KEY,
  label text NOT NULL,
  sort_order int NOT NULL,
  active boolean NOT NULL DEFAULT true
);
ALTER TABLE orders ADD COLUMN status text REFERENCES order_status(code);
UPDATE orders SET status = 'pending' WHERE status IS NULL;   -- backfill
ALTER TABLE orders ALTER COLUMN status SET NOT NULL;

Adding a value is an INSERT: no DDL, no deploy. It carries label, sort order and an active flag, which the other two cannot. The costs are a join for the label and an FK check per insert (an index lookup against a table small enough to stay in cache). Cache the whole thing in the app; it is a handful of rows.

change costattributesreferenced elsewherestorage
CHECKmigration, no scannonotext
native enumadd is fine, remove/reorder painfulnoone type shared across tables4 bytes
lookup tableINSERTyesyes, by FKtext + join

The option to reject. Unconstrained text enforced only in application code. Detection is one query: SELECT status, count(*) FROM orders GROUP BY 1 ORDER BY 2 DESC;. The tail is your typos. Adding the constraint afterwards means a cleanup with no record of what the bad values meant.

Two things that decide more than the storage choice. A four-value status is a poor index on its own: 10M rows / 4 values = 2.5M rows per value, so the planner will seq-scan anyway. Index it as (status, created_at), or as a partial index WHERE status = 'pending', which stays small. And if only some transitions are legal, none of the three options has anywhere to put that rule, a trigger or the application owns it, and if the history of transitions matters, you want an append-only order_status_events table rather than an overwritten column.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design a schema for orders and order lines, and explain each decision.

Answer

orders holds what is true of the order: a surrogate id, customer_id as a foreign key, status, placed_at, currency, and a shipping address. order_lines holds id, order_id, product_id, quantity, and unit_price.

The decisions worth defending:

unit_price on the line. This is the price at the time of purchase, which is a genuinely different fact from the product's current price. Reading it through the product would silently rewrite every historical order the next time a price changed. This is not denormalisation.

Address stored on the order, not referenced. Same reasoning: where it was shipped is a historical fact. If the customer's saved address is later edited, past orders must not change. I would store the resolved address on the order, optionally alongside a reference to the address record it came from.

Currency on the order, not the line. An order cannot be partly in euros. Putting it on the order makes mixed-currency lines unrepresentable rather than merely discouraged.

Constraints. quantity with CHECK (quantity > 0); unit_price as numeric with CHECK (unit_price >= 0); status constrained to a known set; order_id foreign key with ON DELETE CASCADE, because a line has no meaning without its order: this is genuine composition; product_id with ON DELETE RESTRICT, because deleting a product must not silently destroy order history.

What I would not store: a line_total column, because it derives from quantity and price in the same row. A generated column if it must be materialised, so it cannot drift. An order_total on the order is a real decision: derivable from the lines, so I would leave it out initially and add it as a generated or trigger-maintained value only if measurement showed the aggregation mattered.

Indexes: order_lines(order_id) for fetching an order's lines, and orders(customer_id, placed_at DESC) for a customer's order history.

The question I would ask before finalising: does the business need to know what an order looked like at an earlier point. For disputes or audit? If so, status changes need an event table rather than an overwritten column, and that is much cheaper to decide now than to retrofit.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How would you model an address, and why is it harder than it looks?

Answer

Addresses are the standard example of a domain where the obvious model is wrong, because almost every 'obvious' rule about them is false somewhere.

Postcodes are not universal and are not numeric: Ireland had none for most addresses until recently, and several countries use letters. 'State' is meaningless in many countries and mandatory in others. Street-number-then-name is not universal ordering. Some addresses have no street. Names and lines contain characters far outside ASCII. So a schema with street_number int, state varchar(2) NOT NULL, postcode varchar(5) is wrong outside one country, and it will be wrong silently: data gets mangled to fit rather than rejected.

My default is flexible: country_code (ISO 3166-1 alpha-2, constrained, and genuinely required. It is the one field that is always meaningful), several free-text lines, plus locality, region and postal_code as optional text. Validation rules then vary by country and live in the application, where they can be updated without a migration, rather than being frozen into column types.

The second thing that makes it hard is that an address is usually a historical fact at the point of use. Where an order shipped must not change when the customer edits their saved address. So the order stores its own resolved copy (that is a snapshot, not denormalisation) optionally alongside a reference to the address record it came from.

Third, addresses are not naturally unique and deduplicating them is a genuinely hard problem: the same physical place has many valid textual forms. I would not attempt exact-match deduplication, and if canonicalisation matters I would use an address-validation service and store both the raw input and the normalised result, since the service's normalisation can change over time.

And fourth, addresses are personal data. They fall under erasure and retention obligations, which interacts awkwardly with the historical-snapshot requirement: worth deciding deliberately rather than discovering during a deletion request.

The general lesson I would draw: when modelling a real-world domain, the cost of being too permissive is some messy data; the cost of being too restrictive is being unable to represent legitimate reality at all. For domains this variable, permissive with application-level validation is the safer error.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How do you model soft deletion, and what does it cost?

Answer

A nullable deleted_at timestamp, which is more useful than a boolean because it records when and sorts naturally. The motivation is recoverability, audit, and preserving referential targets for historical records.

The cost is that every query must now exclude deleted rows, and the failure mode is silent: one forgotten WHERE deleted_at IS NULL leaks deleted data into a listing or inflates a count. I do not rely on discipline for that. The filter is applied once, centrally: a view over the table, row-level security, or a data-access layer where the filtered query is the default and including deleted rows requires an explicit opt-in.

Unique constraints are the second problem, and it is the one people hit first. A plain unique constraint on email blocks re-registering an address belonging to a deleted account. The fix is a partial unique index applying only where deleted_at IS NULL, so uniqueness holds among live rows only.

Third, foreign keys do not understand the flag. The database will happily let a live child reference a soft-deleted parent, because the row is still there. That has to be an application rule and needs a deliberate decision: cascade the soft delete, block it, or accept it explicitly.

Fourth, growth: deleted rows sit in the table and every index forever, degrading scans and inflating index size. A partial index excluding them helps reads but not storage.

And fifth, privacy: an erasure request under GDPR or similar means actual removal, not a flag. So soft deletion usually needs pairing with a retention job that hard-deletes or anonymises after a defined window, which also bounds the growth problem.

When the real requirement is audit history rather than undo, an append-only history table is usually the better design, because it records what changed and by whom rather than merely that a row is gone.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

How would you model data that changes over time so history is preserved?

Answer

First I establish what question history must answer, because the approaches differ sharply and picking wrong is expensive.

'What is the current value, and what were the previous ones' is different from 'what did the whole record look like on this date', which is different again from 'who changed what, when, and why'.

Append-only event log. Every change is a new row: entity, field or payload, timestamp, actor, reason. Current state is derived from the latest event, or maintained as a projection. This is the most faithful (it records the change, including who and why, which the other approaches lose) and it composes well with auditing. The cost is that reading current state requires either a query per entity or a maintained projection, and the projection is denormalisation with all the drift obligations that carries.

Validity ranges (slowly changing dimension type 2). Each row carries valid_from and valid_to, with the current row having an open end. 'As of' queries are then a simple range predicate, which is the big advantage. The subtleties: an exclusion constraint to prevent overlapping periods for the same entity, a partial unique index to enforce exactly one open row per entity, and a decision about whether ranges are half-open. They should be, or boundary instants belong to two rows.

Shadow history table. The main table stays current and a trigger copies the previous version into a history table on update. Simple, transparent to existing queries, and it works well for audit-only needs. It is weaker for point-in-time reconstruction across related tables, because the histories are independent and reconstructing a consistent moment across several of them is genuinely hard.

My default for audit is the event log; for 'as of' reporting, validity ranges; and I will use both when the requirements genuinely differ.

What I would flag regardless: history tables grow without bound, so a retention policy is part of the design, not an afterthought. And legal erasure obligations conflict directly with immutable history, so the design needs a defined way to redact a subject's data from history while preserving the structural record, decided up front rather than discovered during a deletion request.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Explain when a wide table is better than several narrow ones.

Answer

The default is one table per entity, with columns that are genuinely attributes of that entity. Splitting is worth considering in a few specific situations, and worth resisting in most others.

Split when the columns have different lifecycles or access patterns. A users table read on every request, alongside a rarely-read blob of preferences or a large profile text, is a case for separating them: the hot table's rows stay narrow, so more of them fit per page and more of the working set stays cached. This is the strongest argument and it is a measurable one.

Split when access control differs. If some columns are sensitive and should be readable by fewer roles, a separate table makes that enforceable with table-level grants rather than relying on every query selecting carefully. Column-level grants exist but table separation is harder to get wrong.

Split when the columns are genuinely optional and belong to a subtype. If half the columns apply only to one kind of entity, that is not a wide table, it is two entities sharing one, and separate tables, or a documented single-table-inheritance pattern, expresses it honestly.

Keep it wide when the columns are simply attributes of the same thing. Splitting a coherent entity across tables to reduce column count adds a join to every read, adds a foreign key to maintain, and creates the possibility of a missing child row: a new invalid state that did not previously exist. That last point is the one people miss: a one-to-one split introduces the question 'what does it mean when the second row is absent', and now every reader must answer it.

One engine-specific note worth knowing: PostgreSQL already stores large values out of line automatically, so a big text column does not bloat every row read the way people assume. That weakens the most commonly cited reason for splitting, and is worth checking rather than assuming.

So my test is whether the split is justified by a measured access pattern or a security boundary. 'This table has a lot of columns' is not by itself a problem: a hundred columns that are all genuinely attributes of one entity is fine, whereas twenty columns describing three different things is not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

When is a JSON column the right choice, and what do you give up?

Answer

A native JSON type (jsonb, which stores a parsed binary form and supports indexing) earns its place in three cases. Genuinely variable attributes that differ per row, such as per-integration settings or product attributes across unlike categories. Opaque third-party payloads captured verbatim for audit or replay, where the shape is not yours to define. And sparse optional fields where a hundred mostly-null columns would be worse.

What you give up is everything the relational model provides. The database cannot enforce that a field is present, is the right type, or references a real row: no NOT NULL, no foreign keys into a document, and CHECK constraints on inner fields only with extra effort. Every consumer must handle every shape the column has ever held, and because there is no schema to consult and no migration to run, drift is invisible until something breaks. Queries are more verbose and easier to get subtly wrong, and the planner estimates selectivity on JSON predicates poorly, which produces bad plans on large tables.

Indexing works but is a deliberate choice rather than automatic: a GIN index for containment and key-existence queries, or an expression B-tree index on a specific extracted path when one field is queried like a column.

My rule: if a field is frequently queried, joined, aggregated or needs ordinary relational constraints, promote it to a column; occasional JSON predicates remain legitimate and can be indexed. JSON is for data that is genuinely variable or genuinely opaque.

The failure mode I look for in review is a JSON blob whose keys are in fact fixed and known. That is a table someone did not want to write a migration for, and it costs far more later than the migration would have: every consumer reimplements validation, nothing catches a typo'd key, and the eventual extraction into columns is a migration plus a backfill plus a long tail of edge cases.

The useful middle ground is promoting hot fields to real columns, generated from the JSON where the payload remains the source of truth, so they can be constrained and indexed normally while the original document is retained.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How do you decide which indexes a new schema needs?

Answer

From the access patterns, not from the columns. An index exists to serve a query, so if I cannot name the query it serves, it should not exist.

The ones I create with the schema, because they are structural rather than speculative: primary keys, which are indexed automatically; unique constraints, likewise; and every foreign key column, which is not automatic in PostgreSQL and catches people out. Without it, looking up a parent's children scans, and, more damaging, deleting or updating a parent must check for referencing rows, which scans the child table each time.

Then I work through the known queries. For a composite index, equality-first is a useful starting heuristic, followed by a range or ordering column, but the workload, selectivity and engine features determine the final order. A range often limits how later columns contribute to scan bounds. WHERE tenant_id = ? AND created_at > ? ORDER BY created_at DESC wants (tenant_id, created_at DESC).

Beyond that: a partial index when queries only ever touch a subset, which keeps it much smaller. Indexing only unprocessed rows in a queue table is the classic case. An expression index when a query filters on a transformation, since wrapping a column in a function otherwise defeats the plain index. A covering index when it lets a hot query be answered from the index alone.

Against all of it, every index taxes every write on that table, consumes storage, and adds vacuum work. So I start with the structural ones plus the indexes for known critical queries, and add the rest against measured evidence rather than anticipation.

The checks I run afterwards: are any two indexes redundant. An index on (a) may be functionally covered by (a, b) but can still differ in size or definition, and is anything unused? Both are pure cost. Most mature databases carry several indexes nobody has needed for years, and removing them is a real if unglamorous win.

One caveat specific to schema creation: building an index on a large existing table locks writes unless built concurrently, so on a busy populated table where blocking writes is unacceptable, that is the usual safe route.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

A customer may have at most one active subscription, and no two bookings for the same room may overlap in time. How would you enforce rules like these in the database?

Answer

A CHECK constraint only sees the row it is attached to, so a rule that spans rows (at most one active subscription per customer, no overlapping bookings for a room) has to be enforced by something that can see the other rows at write time. In PostgreSQL the two mechanisms that actually hold under concurrent writes are a partial unique index and an exclusion constraint. Triggers and guard columns work only if you add explicit locking, and deferred constraints change when the error surfaces, not whether the race exists.

Partial unique index. For the subscription rule:

sql CREATE UNIQUE INDEX one_active_sub ON subscription (customer_id) WHERE status = 'active';

The index contains only rows where the predicate is true, so a customer can have many cancelled rows and exactly one active one. Under concurrency it is safe: two transactions inserting an active row for the same customer both try to insert the same index tuple. The second blocks on the first's uncommitted tuple and, when the first commits, fails with unique_violation; if the first rolls back, the second proceeds. The predicate must be immutable: WHERE status = 'active' is fine, WHERE now() < end_at is not, because the index would go stale as time passes.

Exclusion constraint. For bookings:

sql CREATE EXTENSION btree_gist; ALTER TABLE booking ADD CONSTRAINT no_overlap EXCLUDE USING gist (room_id WITH =, tstzrange(start_at, end_at, '[)') WITH &&);

This is a GiST index over the pair; two rows conflict when the room ids are equal and the ranges overlap. Same blocking behaviour as the unique index, so it is safe under concurrency. Costs: GiST maintenance is heavier than btree, you need the extension, and the constraint cannot be deferred. PostgreSQL rejects DEFERRABLE on exclusion constraints, so a transaction that temporarily overlaps must be split or the rows inserted in a non-overlapping order.

Deferred constraints. UNIQUE ... DEFERRABLE INITIALLY DEFERRED lets a transaction swap two values and check only at COMMIT. It does not remove the race: the index still takes the same lock, the error just arrives at COMMIT instead of at the statement, which makes it harder to attribute. Use it for multi-statement reshuffles, not as a concurrency fix.

Triggers. A BEFORE INSERT trigger that runs SELECT count(*) ... WHERE status = 'active' is not safe: two concurrent transactions both read zero and both insert. To make it safe the trigger must take a lock that serialises the conflicting writers: SELECT ... FROM customer WHERE id = NEW.customer_id FOR UPDATE, or pg_advisory_xact_lock(hashtext(NEW.customer_id::text)). That works, but it serialises all writes for that customer and the lock is invisible in the query plan. Reach for it only when the rule cannot be expressed as an index: "at most three active subscriptions", or a rule that joins another table.

Guard column. A customer.active_subscription_id with a unique index is the same mechanism as the partial index, just denormalised. Useful when the "active" definition is expensive to compute, but it must be maintained by the same transaction that changes the subscription, and it drifts if any write path forgets.

MechanismSafe under concurrency?Cost
Partial unique indexYesOne index; write amplification on indexed columns
Exclusion constraintYesGiST index, extension, not deferrable
Deferred uniqueYes, error at COMMITLonger lock hold, harder to debug
Naive triggerNo—
Trigger + row/advisory lockYesSerialises per key; invisible locking
Guard columnYes if maintainedDrift risk, extra write path

One failure mode worth naming: the partial index silently stops applying if the predicate column is nullable and rows carry NULL status. NULL never matches status = 'active', so those rows escape the constraint entirely. Make the column NOT NULL.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How would you model a hierarchy (an org chart, a product category tree, a comment thread) in a relational schema? Compare the common approaches and say which you'd pick for a shallow tree that's read constantly versus a deep tree that's edited often.

Answer

Four ways to store a tree, and they differ almost entirely in where they put the cost.

Adjacency list: parent_id on the row. Insert and move are a single-row update, O(1). Reading a subtree needs a recursive CTE: one index probe per level, one row per descendant.

sql CREATE TABLE category ( id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY, parent_id bigint REFERENCES category(id), name text NOT NULL, CHECK (id <> parent_id) ); CREATE INDEX ON category (parent_id);

WITH RECURSIVE subtree AS ( SELECT id, parent_id, 0 AS depth FROM category WHERE id = $1 UNION ALL SELECT c.id, c.parent_id, s.depth + 1 FROM category c JOIN subtree s ON c.parent_id = s.id ) SELECT * FROM subtree;

Materialized path: store '1.4.9' in a text column. Subtree read is one index range scan (path LIKE '1.4.%'), no recursion. Moving a node rewrites the path of every descendant.

Closure table: a second table with one row per (ancestor, descendant) pair, including self-pairs at depth 0. Subtree read is a single join. Inserting a leaf writes depth+1 rows; moving a subtree deletes and reinserts subtree × ancestors rows.

Nested sets: left/right integers. Subtree read is one range scan. Any insert or move renumbers O(n) rows, and two concurrent inserts corrupt the numbering unless serialised.

subtree readinsert leafmove subtree
adjacency listrecursive, d probes1 row1 row
materialized path1 range scan1 rowO(subtree)
closure table1 joinO(depth) rowsO(subtree × ancestors)
nested sets1 range scanO(n) rowsO(n) rows

Which to pick. Shallow tree read constantly: product categories, 3–4 levels, read on every page render: materialized path. The read is a single index range scan with no recursion, and because the tree is shallow a move rewrites only a handful of rows. Adjacency list is the acceptable simpler answer if you'd rather not maintain the path; the recursion is bounded at 4 levels.

Deep tree edited often: a comment thread, or an org chart that gets reorganised: adjacency list. A move is one UPDATE and nothing else comes close on writes. You pay on reads, so cache the subtree or the ancestor chain.

Closure table is the pick when reads dominate, moves are rare, and the tree is deep: one join gives any subtree or any ancestor chain, and you pay O(depth) per insert.

Preventing a node from becoming its own ancestor. CHECK (id <> parent_id) stops only the one-row self-loop; a cycle of length 3 passes it. With a closure table the check is natural: before moving X under P, ask whether X is already an ancestor of P:

sql SELECT 1 FROM category_closure WHERE ancestor_id = $X AND descendant_id = $P; -- any row: reject the move

Do the check and the rewrite in one transaction. The closure rows are the invariant, so a cycle cannot be represented without violating CHECK (ancestor_id <> descendant_id). With an adjacency list you have no such invariant: you either detect cycles at read time (Postgres 14+ WITH RECURSIVE ... CYCLE) or enforce it in a trigger, and a trigger is easy to bypass with a bulk load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How would you design a multi-tenant schema?

Answer

Three approaches, and the choice is driven by isolation requirements and tenant count more than by anything technical.

Shared tables with a tenant_id column. One schema, a tenant discriminator on every table. Cheapest to operate, scales to very many tenants, and migrations run once. The risk is that a single forgotten WHERE tenant_id = ? leaks one customer's data to another: the most serious bug this system can have, and one that returns plausible-looking results rather than an error. So the predicate must be enforced structurally: row-level security, so the database applies it regardless of the query, or a data-access layer where an unscoped query is impossible to write. Not a code-review convention.

Schema per tenant. Stronger isolation, per-tenant backup and restore, easier to reason about. The cost is that migrations must run across every schema, which becomes genuinely painful in the hundreds and untenable in the thousands, and connection and catalogue overhead grows.

Database per tenant. Strongest isolation, per-tenant tuning and residency, straightforward deletion. Highest operational cost per tenant, so it suits few large tenants, strict regulatory separation, or data-residency requirements.

My default is shared tables with row-level security, moving specific tenants to isolated databases when a contract or regulation requires it: a hybrid is normal and worth designing for rather than treating as failure.

The issue that dominates in practice is tenant skew. Tenant sizes are extremely uneven: the largest may hold thousands of times the median's data. Indexes must lead with tenant_id so queries prune to one tenant; a plan tuned on the median tenant can be badly wrong for the largest; and one enormous tenant can degrade shared resources for everyone, which is a noisy-neighbour problem needing per-tenant limits rather than a schema fix.

Two more things I would design in from the start, because retrofitting both is painful: tenant deletion, which under shared tables is a large cascading delete needing batching, and per-tenant data export, which customers ask for and which is trivial in isolated databases and fiddly in shared ones.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

What are the structural trade-offs between a Star Schema and a Snowflake Schema when designing dimensional models for analytical workloads?

Answer

What I'd say first: Default to a star. Flatten every dimension into one table keyed by a surrogate key and let the fact table join directly to it. Snowflake only when a sub-dimension is genuinely shared across several dimensions with its own SCD lifecycle, or when a frequently-changing parent attribute would otherwise force a rewrite of a very large child dimension. The historical storage argument for snowflaking no longer holds in columnar engines.

The structural difference. Star: dim_product carries product, subcategory, category, brand and department attributes on one row. Snowflake: dim_product → dim_subcategory → dim_category, and the fact table joins to the leaf.

StarSnowflake
Dimension shapeOne flat table per dimension3NF hierarchy of tables
Tables/joins for a 4-dimension query4 tables, 3 joins9 tables, 8 joins
Planner join-order search space4! = 249! = 362,880
Parent attribute updateRewrite every child rowUpdate one parent row
Columnar storageDictionary-encoded, roughly equalRoughly equal

Storage arithmetic (worked; assumptions labelled). Take the geography portion of dim_customer, 20M rows, denormalized: city 24 B, state 16 B, country 16 B, region 12 B = 68 B/row → 1.36 GB. Normalized: dim_geography holds ~40,000 distinct city/state/country/region combinations at 68 B ≈ 2.7 MB, and dim_customer carries a 4-byte geo_key → 80 MB. Total ≈ 83 MB, a 16× reduction.

Now the same table in a columnar store with dictionary encoding: each column stores its distinct values once plus a per-row index. city ~10,000 distinct → 2 B index; state 50 → 1 B; country 200 → 1 B; region 10 → 1 B. That is 5 B/row × 20M = 100 MB: within 20% of the normalized 83 MB, with no extra joins. That is why the storage case for snowflaking is gone.

What the engine actually does. Oracle's star transformation rewrites a star query into a bitmap AND: it scans each dimension for the filtered keys, probes bitmap indexes on the fact table's foreign keys, intersects the bitmaps, then touches fact rows. It needs a bitmap index per fact foreign key and pays off when the dimension filters are selective. A snowflaked query has no single fact-side bitmap per dimension, so the planner must estimate selectivity through the chain and pick a join order.

Trace: SELECT p.category_name, SUM(f.net_amount) FROM fact_sales f JOIN dim_product p ON f.product_key=p.product_key JOIN dim_store s ON f.store_key=s.store_key JOIN dim_date d ON f.date_key=d.date_key WHERE d.year=2024 AND s.country='US' GROUP BY 1; Star: 3 joins, dimensions filtered first, hash tables built on the small filtered key sets. Snowflaked: 8 joins, and if the planner underestimates the dim_city → dim_state fan-out it can build the hash table on the wrong side and spill.

Failure modes.

  • Snowflake, join-order misestimation: EXPLAIN shows a large hash build or a nested loop over the fact table. Fix with a flattened reporting dimension or a materialized view.
  • Star, SCD update amplification: renaming a category rewrites all 200,000 dim_product rows under SCD Type 1. Detect via row counts on the dimension update; mitigate by versioning the parent only.
  • Star, wide dimensions: a 200-column dimension slows full scans and BI metadata load.
  • Snowflake, BI fan-out: auto-generated joins across a chained hierarchy duplicate fact rows if a level is many-to-many.

When snowflaking wins. Shared sub-dimensions (dim_geography reused by store, customer and vendor) with distinct SCD lifecycles: normalize once, conform everywhere. And extreme update skew: 10 categories denormalized across 100M product rows means a category rename rewrites 100M rows; a normalized dim_category makes it one row.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

When would you denormalise, and what obligations does that create?

Answer

I denormalise when a measured read pattern demands it, not pre-emptively. The trigger is a real query that is genuinely too slow after the ordinary remedies (indexes, better predicates, a rewritten join) have been tried.

Before duplicating anything I ask whether it is the same fact or a snapshot of a fact. An order line's price at purchase is a distinct fact and belongs there normalised. A copy of the customer's current email on the order is redundancy. Those two look identical in the schema and are completely different decisions.

When it is genuine redundancy, I take on responsibility for consistency and must name the mechanism. A generated column, where the database derives it from the same row, is the best option because drift is impossible. A trigger works when the source is another table, at the cost of hidden write-path behaviour. An application transaction updating both is acceptable if it is genuinely the only writer, which it rarely stays. A scheduled recomputation is fine when bounded staleness is acceptable.

What is never acceptable is 'the application will keep them in sync' with no enforcement, because the second writer (a migration, a backfill, an admin action) will not know.

And whatever the mechanism, I add a reconciliation check that recomputes the derived value for a sample and alerts on divergence. Denormalised data drifts; the difference between a maintained denormalisation and a rotting one is whether anything checks. A cached count that has been wrong for eight months is worse than no cached count, because people trust it.

I also write down why it exists, next to the column. Otherwise someone later sees a redundant column, correctly identifies it as a normalisation violation, and removes it: reintroducing the performance problem the duplication was solving.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Explain the trade-offs of table partitioning as a schema decision.

Answer

Partitioning splits one logical table into physical partitions by a key: usually a date range, sometimes a hash or a list. It is a physical design decision that shows up as a schema constraint, which is why it belongs in this conversation rather than purely in tuning.

Where it genuinely helps: dropping old data. Deleting a month of rows from a huge table is an expensive operation that leaves bloat behind; detaching a monthly partition is near-instant and reclaims the space immediately. For time-series data with a retention policy, that alone justifies it.

It also helps through partition pruning, a query filtered on the partition key skips irrelevant partitions entirely, and by keeping indexes per-partition, so each is smaller and more cacheable. Bulk loading and maintenance can be done per partition too.

What it constrains is the part people underestimate. Any unique constraint must include the partition key, because uniqueness is enforced per partition. So a globally unique email on a table partitioned by created month is simply not expressible: a real modelling constraint that often decides whether partitioning is viable at all. Foreign keys referencing a partitioned table have historically been limited, so relationships need checking against your engine's version. Queries that do not filter on the partition key touch every partition, which is worse than an unpartitioned table. And partition management is ongoing work: new periods need creating, which means automation, and a missing future partition causes insert failures at midnight on a boundary.

So my test is: is there a natural partition key that most queries filter on, and a retention or archival requirement? Both, ideally. With only the first, indexes usually suffice. With neither, partitioning adds operational burden and constraints for no benefit, and it is frequently proposed for tables that are simply large, where the actual problem is a missing index.

I would not partition pre-emptively. The conversion is doable later, and the constraints it imposes are easier to accept when the need is demonstrated rather than anticipated.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How would you add a required column to a large live table without downtime?

Answer

The naive single statement (add the column, NOT NULL, with a default) is what causes the outage on older engines, because it rewrites every row under an exclusive lock. Modern PostgreSQL stores a non-volatile default in the catalogue and avoids the rewrite, but I would not rely on version-specific behaviour for a table that matters. The expand–migrate–contract sequence is safe regardless.

Expand. Add the column nullable with no default. A fast catalogue-only change.

Migrate, in two separate deploys. First deploy code that writes the column on every insert and update but does not require it when reading. Then backfill existing rows in bounded batches with a pause between them, so no single transaction holds locks long or generates unmanageable WAL. Then, once no NULLs remain, add the constraint: as NOT VALID and validated separately where supported, so the scan does not block writes. Only then deploy code that depends on the column being present.

The reason the write and read steps must be separate deployments is that during a rollout both versions run concurrently, and rollback must stay safe: no deployed version may require something a version it could roll back to does not write.

Contract. Remove any now-dead code and defaults.

Operationally: rehearse on a production-sized copy and measure the backfill rate there; monitor replication lag during the backfill, because a large one can push replicas far behind and that is often the first thing to actually break; pick a low-traffic window; and make the backfill resumable and idempotent so a failure mid-run is re-runnable rather than needing manual reconciliation.

If the table is so large that even batched backfill is impractical, the fallback is a shadow table with triggered dual writes and an atomic rename at the end: considerably more work, so I would exhaust the batched approach first.

The thing I would insist on regardless of size: each step independently reversible, and no step that cannot be abandoned halfway.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How would you approach a legacy schema with no constraints and inconsistent data?

Answer

Incrementally, and with measurement before any change, because the instinct to 'fix the schema' in one pass fails: the data already violates the rules, so every constraint addition is a cleanup project, and doing them all at once means a long outage and a large blast radius.

First, measure the violations. For each rule I believe should hold, write a query counting the rows that break it. This is cheap, non-destructive, and it converts an anxiety into a work item with a size. It also frequently reveals that a rule I assumed was intended is routinely violated on purpose, which is a requirements conversation, not a data problem, and much better discovered now.

Second, stop the bleeding. Before cleaning history, ensure new writes are valid: application validation as an immediate measure, then the constraint itself. There is no point cleaning rows while the source keeps producing more.

Third, prioritise. Rules protecting money, identity or safety first. Rules whose violation is currently causing incidents next. Cosmetic normalisation last, or never: a legacy schema does not need to reach a normal form to be safe, and pursuing that is how remediation projects lose support.

Fourth, clean and constrain one rule at a time. For each: decide what the invalid rows mean (genuinely bad, or a legitimate case the rule got wrong) then fix or exempt them, then add the constraint NOT VALID, then validate. Small independent steps, each shippable and reversible.

The decision about what an invalid row means is the hard part and it is not a technical one. It needs someone with domain context, and for old data that person may no longer be available: in which case the honest options are to preserve the rows behind an exemption rather than guess, or to have the business explicitly accept a lossy correction.

Throughout I would resist the rewrite temptation. A new correct schema alongside the old requires dual writes, a full migration, and cutover: sometimes right, but it should be a deliberate decision with a business case, not the default reaction to finding the existing schema unpleasant.

And I would add the measurement queries as a scheduled check, so violations are visible over time and the direction of travel is known rather than assumed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

What schema decisions most often cause problems later?

Answer

The expensive mistakes share a property: they are cheap to get right at the start and very expensive to correct once data exists and code depends on it.

Not modelling history when it will be needed. A schema that overwrites in place destroys the past irrecoverably. The structure can be retrofitted; the data cannot. This is the only one on the list where the damage is permanent, which is why it is first.

Missing constraints. Data that was never constrained is data that is already invalid by the time you try to constrain it, so adding the constraint means a cleanup project first, and that cleanup requires decisions nobody has context for any more.

Money as floating point. Totals become irreproducible and drift, and correcting it means a type change plus reconciling every derived figure ever reported.

Timestamps without time zones. Ambiguous during daylight-saving transitions, and the original intent cannot be recovered once written: you cannot tell which zone a naive timestamp meant.

Natural keys as primary keys. Fine until the identifier changes, then it cascades through every referencing table and every external system that stored it.

Enumerations as native enum types where values change frequently: each change is a schema migration. A lookup table costs one join and removes that.

JSON where columns belonged. Every consumer reimplements validation, no typo is caught, and extraction later is a migration plus backfill plus a long tail.

Exposing sequential identifiers publicly. Leaks volume and permits enumeration, and changing public identifiers later breaks every external reference.

The common thread is that all of them are reversible in structure but not in data or in the external commitments made in the meantime. So the questions I push hardest on at design time are: will anyone ask what this looked like in the past; what invalid states does this permit; and what have we committed to externally that we cannot change.

I would add that being wrong about performance is usually cheap: you add an index. Being wrong about meaning is expensive.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain how you would test a schema.

Answer

The thing worth testing about a schema is its negative space: that invalid data is genuinely rejected. A constraint that was never exercised may not do what its author intended, and constraints are unusually easy to get subtly wrong: a CHECK with a NULL-permitting predicate passes for NULL rows, and a unique constraint on the wrong column combination looks right until duplicates appear.

So for each constraint I write a test asserting the invalid insert fails: a null in a required column, a duplicate natural key, a foreign key to a nonexistent parent, a negative quantity, an end date before its start, a second active row where only one is allowed, an overlapping range. Each should raise, and asserting on the constraint name rather than just 'it threw' confirms the intended constraint fired rather than an unrelated one.

I test referential actions explicitly, because they are decisions and are easy to get backwards: deleting a parent with children should cascade or restrict according to design, and a test that asserts which one is what stops a later migration silently changing it.

I test migrations by running them forward against a production-shaped copy, asserting both the resulting schema and, for anything with a backfill, that the backfilled values are correct. A migration that produces the right structure and wrong data is a common and quiet failure.

I also test the concurrent behaviour of anything meant to be race-safe: two overlapping transactions both attempting the same insert, asserting exactly one succeeds. Sequential tests cannot catch a check-then-insert race, and that race is precisely what the constraint exists to prevent, so a test that does not exercise concurrency is not testing the thing that matters.

All of this against the same engine and version as production, since constraint semantics, NULL handling in unique constraints, and lock behaviour all vary between engines.

And for a schema still under design, the most valuable exercise is not automated: take the invalid states you are worried about and try to insert them by hand. Whatever succeeds is a missing constraint.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Describe how you would document a schema so it stays useful.

Answer

The structure documents itself if it is well designed: names, types and constraints say what is stored and what is valid. What is never recoverable from the structure is why, and that is what documentation has to carry.

So I document the decisions, not the columns. A COMMENT ON COLUMN saying 'the customer's email address' on a column called customer_email is noise that will drift. A comment saying 'denormalised from customers.email for the daily digest query; maintained by the trigger below; reconciliation job checks it nightly' is information that cannot be inferred and that prevents someone correctly identifying it as redundancy and deleting it.

The things genuinely worth writing down: why a denormalisation exists and what maintains it; why a constraint is absent where one would be expected, which is otherwise indistinguishable from an oversight; what an ambiguous column actually means, especially units, time zones and whether an amount is gross or net; and which of several similar tables is authoritative.

I keep it as close to the schema as possible. Database comments live with the object and survive being read through a client. Migration files are a natural place for the reasoning behind a change and are already reviewed. A separate wiki page is where schema documentation goes to die, because nothing forces it to change when the schema does.

For the overview, a generated entity-relationship diagram is worth more than a hand-drawn one, precisely because it cannot go stale. Hand-maintained diagrams are wrong within months and are then actively misleading, which is worse than having none.

The test I apply: if a competent engineer who has never seen this system reads the schema plus its comments, what would still surprise them? Those surprises are exactly what needs documenting, and it is a much better prompt than trying to describe everything.

And the strongest form of documentation remains making the wrong thing impossible. A constraint that prevents an invalid state does not need a comment explaining that the state is invalid.

Curated: · Written: · Reviewed:

Difficulty: Medium