Data Modeling and Schema Design Questions
Designing relational schemas end to end: entity-relationship modeling, normal forms and deliberate denormalization, primary/foreign keys, data types, and integrity constraints, together with applied schema design driven by real business requirements and query access patterns. Covers modeling a domain from ambiguous requirements, choosing structures that serve the queries a system must run, trading normalization for correctness against denormalization for read performance, and evolving schemas as needs change. Foundational data-modeling judgment for building and reviewing databases, tested through open-ended domain-modeling prompts.
Propose schema patterns to add auditing and change-tracking to tables for traceability. What columns and structures would you add to capture who changed a row and when, and what approach would you use for row-level history: a separate audit table, database-level change data capture, or an append-only pattern? Discuss the queryability and performance trade-offs of each history-tracking approach.
Sample Answer
Direct answer
The three realistic options for row-level change history are a separate audit table (one row per change, referencing the original table), database-level change-data-capture (CDC, reading the write-ahead log independently of the application), or an append-only pattern (the "table" itself is a log of versions, with the current state being the latest version per key); the right choice trades off write-path coupling against query convenience.
Structured elaboration
- Separate audit table (
orders_audit(audit_id, order_id, changed_by, changed_at, change_reason, old_values, new_values)), populated either by a trigger onordersor by explicit application-level writes alongside the main update. Simple to query directly ("show me the history of this order"), but a trigger-based implementation couples every write's latency to the trigger's cost, and an application-level implementation risks missing history if some code path updates the table without remembering to also write the audit row. - Database-level CDC (reading the write-ahead log or a logical-replication stream, e.g., via Debezium, entirely outside the application): captures every change regardless of which application code path made it (closing the "forgot to log it" gap), decoupled from the write's own transaction latency, but the history lives in a separate downstream system (a Kafka topic, a sink table) rather than directly queryable alongside the source table without additional plumbing.
- Append-only pattern (never
UPDATEin place; every change is a new row, and "current" is whichever row for a given key has the latest timestamp or highest version number): the history IS the table, so there's no risk of forgetting to log a change, and querying "state as of time T" is a natural filter; the trade-off is that every ordinary read of "current state" now needs a filter or a materialized "current" view to avoid scanning the entire history.
Worked example
For created_by/created_at/updated_by/updated_at as always-present columns: these answer "who last touched this row and when" cheaply for the CURRENT row, but they overwrite prior history on every update, so they are not a substitute for any of the three mechanisms above if you need to see the full sequence of past changes, only a complement to them for the common, cheaper case of "who changed this most recently."
Trade-offs and pitfalls
- The trigger-based audit table is the most common production pattern because it's the most directly queryable, but it's also the easiest to accidentally bypass: a bulk
UPDATErun directly against the database by an operator, or a data-migration script, can skip the application code path the audit-table logic assumed was the only writer, silently leaving a gap in the history. - CDC closes that "forgot to log it" gap completely (it reads the actual write-ahead log, not application intent), which is exactly why it's the more robust choice when auditability is a compliance requirement rather than a convenience feature, at the cost of the history living in a separate system that needs its own query tooling.
- The append-only pattern's "no UPDATE ever" discipline is the strongest guarantee of the three (there is structurally no way to lose history, since nothing is ever overwritten), but it pushes real complexity onto every reader that wants current state, and it requires a clear convention (a version number, or a
is_currentflag maintained carefully) to avoid every query needing to compute "which row is the latest" itself.
Discuss schema-first (normalized) versus query-driven, denormalized modeling for a microservice that must support ad-hoc queries from downstream analytics teams. Recommend an approach and explain how you would balance developer productivity, query performance, and maintainability.
Sample Answer
Direct answer
Schema-first (normalized) modeling optimizes for write correctness and long-term maintainability at the cost of query flexibility for unanticipated analytics needs; query-driven, denormalized modeling optimizes for the specific known queries at the cost of being harder to evolve if those queries change; for a microservice serving both its own transactional needs and ad hoc downstream analytics, the right balance is usually schema-first for the service's own operational data, with a separate, query-driven denormalized layer built specifically for the analytics consumers.
Structured elaboration
- Schema-first (normalized): model the domain's true entities and relationships first, driven by what the data actually IS, not by any one query's convenience; this keeps the service's own write path simple and correct (one place to update any given fact) and is resilient to future, not-yet-known query needs, at the cost of every non-trivial analytical query needing multiple joins.
- Query-driven (denormalized): model the schema around the SPECIFIC queries you already know you need to serve, often producing wide, pre-joined tables; this makes those specific queries fast and simple, at the cost of the schema being brittle to any query pattern not anticipated when it was designed, and at the cost of write-path complexity (keeping the denormalized shape consistent with the true source of facts).
- Balancing productivity, performance, and maintainability: developer productivity favors schema-first for the service's OWN code (a clean, normalized domain model is easier for the team to reason about and evolve); query performance for KNOWN, high-value analytics queries favors a denormalized layer; maintainability favors keeping exactly one normalized source of truth, with any denormalized layer treated as a derived, rebuildable artifact rather than a second place where facts can independently change.
Worked example
A concrete recommendation: the microservice's own database stays normalized (its own tables model its own domain correctly, optimized for its own transactional writes and reads); a separate, downstream analytics table or warehouse, fed by CDC or a scheduled ETL job from the normalized source, is denormalized specifically around the known analytics queries (a wide, pre-joined "orders with customer and product context" table, say). This keeps the service's own code simple and correct while still giving analytics teams fast, tailored access, without forcing the service's core domain model to compromise for a query pattern that belongs to a different consumer entirely.
Trade-offs and pitfalls
- The temptation to denormalize the service's OWN operational schema (rather than building a separate analytics layer) to make ad hoc queries fast is usually a mistake: it couples the service's write-path correctness to the needs of a downstream consumer, and every future change to the service's own domain model now has to consider its effect on someone else's analytics queries too.
- A separate denormalized analytics layer isn't free: it needs its own pipeline (CDC or ETL) to stay in sync with the normalized source, introduces staleness (the analytics layer lags the live service by however long that pipeline takes), and needs monitoring to catch drift, the same trade-offs as any other denormalization-for-reads decision.
- The right balance shifts with how STABLE the known analytics queries actually are: if the downstream query needs are still evolving rapidly, a query-driven denormalized layer built too early risks becoming outdated before it's even fully built out, and it may be better to serve early-stage analytics needs directly off the normalized source (accepting the join cost) until the query patterns stabilize enough to justify building and maintaining a dedicated denormalized layer.
Design an events table for event-sourcing in PostgreSQL with columns such as event_id, aggregate_id, sequence_num, event_type, payload, and created_at. Explain how you would enforce event ordering per aggregate, implement snapshotting to speed up reads, handle event-schema evolution, and compact or archive old events while preserving auditability.
Sample Answer
Direct answer
An event-sourcing table stores every state-changing event as an immutable, append-only row keyed by (aggregate_id, sequence_num), and current state is derived by replaying (or reading a cached snapshot of) all events for that aggregate, rather than storing current state directly.
Structured elaboration
CREATE TABLE events (
event_id UUID PRIMARY KEY,
aggregate_id UUID NOT NULL,
sequence_num BIGINT NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP NOT NULL,
UNIQUE (aggregate_id, sequence_num)
);
- Ordering per aggregate: the
UNIQUE (aggregate_id, sequence_num)constraint is what enforces strict per-aggregate ordering; a writer must know the next expectedsequence_num(typicallyMAX(sequence_num) + 1for that aggregate, or an optimistic-concurrency check) before appending, and a conflicting concurrent write on the same(aggregate_id, sequence_num)fails the unique constraint rather than silently corrupting order. - Snapshotting: replaying thousands of events to compute current state on every read is slow, so a
snapshots(aggregate_id, as_of_sequence_num, state, created_at)table periodically stores the materialized state as of a given sequence number; reading current state becomes "load the latest snapshot, then replay only the events after it," not the entire history. - Event-schema evolution: because events are immutable and historical, you cannot rewrite an old event's shape when a new event version is introduced; instead, each event carries a
schema_version(often embedded as part ofevent_type, e.g.,OrderPlaced.v2), and the replay/read logic must know how to upcast an old version into the shape the current reader expects. - Compaction/archiving: old events can be archived to cheaper storage once a snapshot has been taken covering them, but only after confirming no reader still needs to replay from before that point; auditability requirements often mean archiving (moving to cold storage) rather than deleting.
Worked example
Verified in sqlite3 (as a stand-in for the ordering guarantee, since JSONB itself is Postgres-specific but the constraint logic is identical): inserting two events for the same aggregate_id with sequence_num = 1 succeeds once and fails on the second attempt with a unique-constraint violation, confirming the schema itself (not application logic) is what prevents two events from claiming the same position in an aggregate's history. Replaying is then just SELECT payload FROM events WHERE aggregate_id = ? AND sequence_num > ? ORDER BY sequence_num, applied on top of the last snapshot's state.
Trade-offs and pitfalls
- The most common design mistake is skipping the uniqueness constraint on
(aggregate_id, sequence_num)and relying purely on application logic to serialize writes; under concurrent requests for the same aggregate, that gap is exactly where two events can be assigned the same sequence position, silently corrupting the replay order. - Snapshotting trades storage and a small amount of read-path complexity (load snapshot, then replay the delta) for bounded read latency; skipping it works fine for a young aggregate with few events, but replay cost grows unboundedly with an aggregate's event count if snapshots are never taken.
- Event-schema evolution is the hardest part of this pattern in practice: every reader of historical events must be able to interpret every version of every event type that has ever existed, which is a much longer-lived compatibility obligation than a normal table's schema migration, where old rows are simply rewritten in place.
Consider this order_items table definition:
order_items(order_id INT, product_id INT, quantity INT, price NUMERIC)
where the combination (order_id, product_id) forms the logical primary key. Explain how composite primary keys work, demonstrate how you'd join this table to orders and products, and describe when you might prefer adding a surrogate key (order_item_id) instead.
Sample Answer
Direct answer
A composite primary key works by combining two or more columns so that the combination is guaranteed unique, even if no single column is; here (order_id, product_id) guarantees a given product appears at most once per order, while still letting the same product appear on many different orders and the same order contain many different products.
Structured elaboration
CREATE TABLE order_items (
order_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
price NUMERIC(10,2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
Joining to orders and products is unaffected by the key being composite: orders joins on order_id, products joins on product_id, exactly as it would with a single-column key:
SELECT o.order_id, p.name, oi.quantity, oi.price
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id;
Worked example
Verified in sqlite3: inserting (order_id=1, product_id=100) twice (say, two separate lines both adding the same product to the same order) fails on the second insert with a primary-key violation, confirming the composite key correctly prevents a duplicate line for the same product on the same order. If the business actually wants to allow two separate lines for the same product on the same order (for example, two different discount codes applied to two units of the same product), that's exactly when you'd prefer a surrogate order_item_id instead: the composite key as given structurally assumes one row per (order, product) pair, which is a real business rule, not just an implementation detail.
Trade-offs and pitfalls
- The composite key here is enforcing a genuine business rule (one line per product per order), not just providing uniqueness for its own sake; if that rule is ever wrong (the two-discount-codes scenario above, or wanting separate lines for auditability), the fix is a surrogate
order_item_idplus, if the one-line-per-product rule still needs to hold in the common case, a separateUNIQUE(order_id, product_id)constraint that can be relaxed later without changing the primary key. - A common mistake is adding a surrogate key "just in case" without checking whether the composite key was already expressing a real invariant worth keeping; dropping the composite uniqueness silently allows the exact duplicate-line bug the original design prevented.
- At scale, a composite key clusters the table by
order_idfirst (in engines that physically order by the primary key), which is usually the right locality for "all items in this order," but means "all orders containing this product" needs a secondary index onproduct_idalone rather than relying on the primary key.
What are the primary components of an entity-relationship (ER) model? Describe entities, attributes, relationships, cardinality, and weak entities, and explain how an ER diagram maps to a normalized relational schema.
Sample Answer
Direct answer
An entity-relationship (ER) model has four building blocks: entities (the things you track, like Customer or Order), attributes (their properties), relationships (how entities associate with each other), and cardinality (how many instances of one entity associate with how many of another). A weak entity is one that cannot be uniquely identified by its own attributes alone and borrows part of its identity from an owning entity.
Structured elaboration
- Entities: independent objects or concepts in the domain (Customer, Order, Product). Drawn as rectangles; each instance is a row once the model becomes a table.
- Attributes: properties of an entity or relationship. They can be simple (atomic, like
email), composite (addresssplit into street/city/zip), multivalued (phone_numbers), or derived (agecomputed frombirth_date). Exactly one attribute (or a combination) is chosen as the identifying key. - Relationships: associations between entity instances (a Customer places an Order). Relationships can be unary (an Employee manages another Employee), binary (the common case), or n-ary (rarer, involving three or more entities at once, such as Supplier-Part-Warehouse).
- Cardinality and participation: cardinality states the maximum number of instances on each side of a relationship (one-to-one, one-to-many, many-to-many); participation states whether that side is mandatory (every instance must participate) or optional.
- Weak entities: an entity with no candidate key of its own. It is existence-dependent on an owning ("strong") entity and its identifier is a composite of the owner's key plus a partial key of its own. Example:
OrderLinecannot be identified without knowing whichOrderit belongs to, so its real key is(order_id, line_number).
Worked example
Consider a simple domain: Customer, Order, and OrderLine.
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ ORDER_LINE : contains
CUSTOMER {
int customer_id PK
string email
string name
}
ORDER {
int order_id PK
int customer_id FK
date placed_at
}
ORDER_LINE {
int order_id FK
int line_number
int product_id
int quantity
}
Mapping this ER model to a normalized relational schema is mechanical:
- Every strong entity becomes a table; its identifying attribute becomes the primary key.
CustomerandOrderare strong entities here. - A one-to-many relationship (Customer places Order) is realized by putting the "one" side's key as a foreign key on the "many" side:
customer_idonorders. - A weak entity (
OrderLine, which cannot exist or be identified without anOrder) becomes a table whose primary key is the composite of the owning entity's key plus the weak entity's own partial key:(order_id, line_number), withorder_idalso carrying anON DELETE CASCADEforeign key, since a line item has no meaning once its order is gone. - Many-to-many relationships (not shown above, but common, like Product-to-Category) become their own junction table with a composite key of the two participants' foreign keys.
Trade-offs and pitfalls
- A common mistake is treating a weak entity's partial key as if it were globally unique on its own (
line_numberalone) instead of scoping it to its owner (order_id, line_number); this silently allows line 1 of order A to collide with line 1 of order B if the composite key isn't enforced. - Mandatory-vs-optional participation is easy to skip during modeling but directly decides whether a foreign-key column is nullable, which in turn affects every downstream query that joins on it.
- Over-eager n-ary relationships are rare in practice; most "three-way" associations decompose cleanly into two binary relationships once you look closely, and forcing a single n-ary relationship where two binary ones would do usually loses information about which pairing caused which fact.
Unlock Full Question Bank
Get access to all Data Modeling and Schema Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.