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.
You inherit a reporting system where two seemingly identical dashboards show different total revenue: one query multiplies quantity by price after joining product tables, while the other sums a precomputed line_total. Given the two queries and schemas, identify the likely root causes (wrong grain, join duplication, a late filter) and propose schema and ETL fixes to make the metrics consistent across dashboards.
Sample Answer
Direct answer
Two dashboards showing different revenue for the same period almost always trace back to one of three causes: a difference in query grain (one multiplies at the line-item level, the other sums a pre-aggregated total), join duplication (a join fanning out rows before the aggregation), or a late/inconsistent filter (one query includes rows the other silently excludes); diagnosing it means comparing the two queries' logic step by step against the actual schema, not just comparing their outputs.
Structured elaboration
- Wrong grain:
SUM(quantity * price)computed after joiningorderstoorder_itemstoproductsoperates at the line-item grain; a separately maintainedline_totalcolumn onorder_items, summed directly, operates at the same grain in principle but can diverge ifline_totalwas computed with different rounding, a different tax treatment, or wasn't updated after a later price correction. - Join duplication: joining
ordersto a table that has more than one row per order (a multi-roworder_promotionstable, say) without first aggregating that side inflates the order's contribution to the sum, effectively double- or triple-counting revenue for any order matching multiple rows on the "many" side of an unexpected fan-out join. - Late filters: a
WHEREclause applied after an aggregation (in aHAVING, or applied only in one of the two dashboard's queries) can silently exclude or include a different set of underlying rows between the two dashboards, even though both claim to report "this month's revenue."
Worked example
A concrete diagnostic process: first, run both underlying queries against the SAME fixed, small time window and compare the total ROW COUNT feeding into each aggregation, not just the final number; if one query's row count is a clean multiple of the other's, that's a strong signal of join duplication (an unexpected fan-out). Second, check whether either total was actually stored (line_total) versus computed on the fly (quantity * price), and directly compare a handful of individual orders' values between the two paths; a discrepancy on specific orders (rather than a broad, roughly-proportional difference) points at a stale or incorrectly-updated precomputed value. Third, diff the two queries' WHERE/HAVING clauses line by line for any filter present in one but not the other (a status != 'cancelled' filter present in one query and missing in the other is a common, easy-to-miss culprit).
Trade-offs and pitfalls
- The most common mistake in this kind of investigation is comparing only the final aggregate numbers and guessing at causes; comparing intermediate ROW COUNTS at each stage of the two queries (before vs after each join, before vs after each filter) isolates exactly which step introduces the divergence, rather than debugging by intuition alone.
- The schema/ETL fix depends on which cause is confirmed: a join-duplication bug is fixed by aggregating the fanning-out side before joining (or using a window function/subquery to pre-aggregate); a stale precomputed total is fixed by adding a consistency check or recomputation step to whatever pipeline maintains it; a filter discrepancy is fixed by centralizing the filter logic (a shared view or a single canonical query both dashboards build on top of) so it can't silently diverge again.
- Preventing recurrence matters as much as fixing this one instance: two independently-hand-written queries computing "the same" metric will drift again eventually; a single, tested, shared definition (a view, a metrics-layer definition, or a well-documented canonical query) that both dashboards consume is the structural fix, not just correcting today's two queries to agree by coincidence.
Design a schema to store customer addresses that supports: a current-address lookup, a historical audit of changes with timestamps, queries like 'what was the address at time T', and efficient deletion and retention. Propose the table(s), primary keys, and indexing strategy, and explain the trade-offs related to storage and query cost.
Sample Answer
Direct answer
Store customer addresses as a small, append-only history table (one row per address version, with an effective date range) rather than a single mutable row, so "current address" and "address at time T" are both simple, indexed queries against the same table, and deletion/retention can target specific historical rows without losing the ability to reconstruct any point in time still within the retention window.
Structured elaboration
CREATE TABLE customer_addresses (
address_history_id BIGINT PRIMARY KEY,
customer_id BIGINT NOT NULL,
line1 TEXT NOT NULL,
city TEXT NOT NULL,
postal_code TEXT NOT NULL,
valid_from TIMESTAMP NOT NULL,
valid_to TIMESTAMP -- NULL means this is the current address
);
CREATE INDEX idx_addr_customer_range ON customer_addresses (customer_id, valid_from, valid_to);
- Current-address lookup:
SELECT * FROM customer_addresses WHERE customer_id = ? AND valid_to IS NULL. - Historical audit of changes:
SELECT * FROM customer_addresses WHERE customer_id = ? ORDER BY valid_from, which shows every address the customer has ever had, in order. - "Address at time T":
SELECT * FROM customer_addresses WHERE customer_id = ? AND valid_from <= ? AND (valid_to IS NULL OR valid_to > ?), the same point-in-time range pattern used for any effective-dated attribute. - Efficient deletion/retention: because each address version is its own row with its own
valid_from/valid_to, a retention policy ("delete address history older than 7 years") can target and delete specific old rows directly (DELETE WHERE valid_to < now() - interval '7 years') without disturbing the current or more recent rows, which a single mutable-column design with no history at all could never support in the first place, since it never had the history to selectively retain or discard.
Worked example
When a customer updates their address, the write is two steps in one transaction: UPDATE customer_addresses SET valid_to = now() WHERE customer_id = ? AND valid_to IS NULL (close out the previous current row), then INSERT the new row with valid_from = now() and valid_to = NULL. This keeps exactly one "current" row per customer at all times (enforceable with a partial unique index, CREATE UNIQUE INDEX ON customer_addresses (customer_id) WHERE valid_to IS NULL), while preserving every prior address indefinitely (or until the retention policy removes it).
Trade-offs and pitfalls
- The storage and query cost of this design is proportional to how often a customer's address actually changes, which for most customers is rare; the cost is well justified given the alternative (a mutable single row) cannot answer "address at time T" or support any auditable history at all, both of which are commonly real requirements (fraud investigation, compliance, shipping-dispute resolution).
- The two-step "close out the old row, insert the new one" write must happen in a single transaction; if a crash or bug leaves a customer with two "current" rows (
valid_to IS NULLon both) or zero, downstream queries assuming exactly one current row will misbehave, which is exactly why the partial unique index enforcing "at most one current row per customer" is worth adding as a schema-level safety net, not just relying on application-level discipline. - Retention and deletion interact with the historical-audit requirement in tension: deleting old rows to satisfy a retention policy permanently forecloses any future "address at time T" query into the deleted range, so the retention window itself needs to be a deliberate compliance/business decision, not an arbitrary storage-saving default.
Design the data model for a messaging app supporting users, conversations, and messages, optimized for these access patterns: (1) list recent conversations for a user with a last-message preview, (2) fetch messages for a conversation with pagination, and (3) handle large-scale message retention and archival. Provide both a relational and a document-store design and explain the trade-offs.
Sample Answer
Direct answer
A messaging app needs conversations, conversation_participants, and messages, with the "recent conversations with last-message preview" query served by denormalizing the last message's summary onto the conversation row, and the choice between a relational and a document-store design turning on how the two access patterns (list conversations vs. paginate one conversation's messages) are weighted against each other.
Structured elaboration
Relational design:
CREATE TABLE conversations (
conversation_id BIGINT PRIMARY KEY,
last_message_preview TEXT,
last_message_at TIMESTAMP
);
CREATE TABLE conversation_participants (
conversation_id BIGINT NOT NULL REFERENCES conversations(conversation_id),
user_id BIGINT NOT NULL,
PRIMARY KEY (conversation_id, user_id)
);
CREATE TABLE messages (
message_id BIGINT PRIMARY KEY,
conversation_id BIGINT NOT NULL REFERENCES conversations(conversation_id),
sender_id BIGINT NOT NULL,
body TEXT NOT NULL,
sent_at TIMESTAMP NOT NULL
);
CREATE INDEX idx_messages_conv_time ON messages (conversation_id, sent_at);
CREATE INDEX idx_participants_user ON conversation_participants (user_id);
- (1) Recent conversations with last-message preview:
conversations.last_message_preview/last_message_atare denormalized (updated on every new message) specifically so listing a user's conversations, joined throughconversation_participants, never needs to separately querymessagesjust to show a preview. - (2) Paginate messages in a conversation: served directly by
idx_messages_conv_time, using keyset pagination (WHERE conversation_id = ? AND sent_at < ? ORDER BY sent_at DESC LIMIT 50) rather than offset-based pagination, which stays fast regardless of how deep into history the user scrolls. - (3) Large-scale retention/archival: partition
messagesby time (monthly), so archiving old messages is a metadata-levelDETACH PARTITIONrather than a slow row-by-row delete, and older partitions can be moved to cheaper storage independently of recent ones.
Document-store design: a conversations collection with an embedded array of the most recent N messages (for the fast preview and initial-load case) plus a separate messages collection referenced by conversation_id for the full, paginated history, exactly the "embed the bounded recent subset, reference the unbounded rest" hybrid pattern, since embedding the FULL message history in one document would eventually hit a document size limit and make every new message rewrite an ever-larger document.
Worked example
Verified in sqlite3 that the denormalized preview approach stays correct across multiple messages: after inserting three messages into a conversation with increasing timestamps, updating conversations.last_message_preview/last_message_at after each insert (as a trigger or application-level step would in production) correctly reflects only the most recent message, and the keyset-paginated query over messages correctly returns the newest 2 messages first when limited, confirming both the preview and pagination paths behave as intended.
Trade-offs and pitfalls
- Denormalizing the last-message preview onto
conversationsrequires a write-side update on every new message; if that update is missed or races with a concurrent message (two messages arriving near-simultaneously), the preview can briefly show a stale or wrong message, which is an acceptable, self-correcting risk for a preview field but would not be for anything requiring strict consistency. - Offset-based pagination (
OFFSET n LIMIT 50) degrades badly for a conversation with a long history, since the database still has to count past the firstnrows on every page; keyset pagination onsent_at(or a monotonic message ID) avoids that entirely and is the right default for chat history specifically. - The relational-vs-document choice here is less about correctness (both can express this domain correctly) and more about which access pattern the underlying store's strengths align with: a relational store's join is cheap and consistent for the participant/conversation relationship, while a document store's embedding wins specifically for the common case of opening a conversation and seeing its recent messages in one read.
Describe partitioning and its benefits for very large tables used in analytics. Explain range, hash, and list partitioning in simple terms and when each is useful. What maintenance operations must you consider for partitioned tables?
Sample Answer
Direct answer
Partitioning splits a large table into smaller physical pieces (partitions) based on a chosen key, so queries and maintenance operations only need to touch the relevant partitions instead of the whole table; the three common schemes are range, hash, and list, chosen by how your queries typically filter the data.
Structured elaboration
- Range partitioning: partitions cover contiguous ranges of a key, most often a date (e.g., one partition per month). Best when queries commonly filter by that range (
WHERE created_at BETWEEN ...), because the planner can skip entire partitions outside the range (partition pruning). - Hash partitioning: a hash function distributes rows evenly across a fixed number of partitions. Best when there's no natural range to filter on and the goal is simply to spread write and storage load evenly, avoiding one partition becoming a hot spot.
- List partitioning: partitions are defined by explicit, discrete values of a key (e.g., one partition per
regionorcountry_code). Best when queries commonly filter on a small, known set of categorical values and you want each category isolated for maintenance (e.g., dropping all data for a deprecated region in one operation).
Worked example
An orders table with billions of rows, mostly queried by recent date range, is a textbook range-partitioning case: PARTITION BY RANGE (created_at) with one partition per month. A query for "orders in March 2026" only scans the March partition, ignoring the other 11+ months entirely (partition pruning), and archiving old data becomes a metadata operation (DETACH PARTITION, then drop or move it to cheap storage) instead of a slow DELETE that has to scan and remove billions of rows one at a time.
Trade-offs and pitfalls
- Maintenance you must plan for: creating new partitions ahead of time (an unpartitioned "future" write will either fail or need a default partition), periodically dropping or archiving old partitions, and keeping per-partition statistics (
ANALYZE/VACUUMin Postgres) up to date, since a huge partitioned table with stale statistics on individual partitions can still produce bad query plans. - A poorly chosen partition key produces the opposite of the intended benefit: range-partitioning by a column that's rarely used in
WHEREclauses means every query still scans every partition, and hash-partitioning on a low-cardinality column can leave some partitions far larger than others (a skewed hot partition). - Partitioning is a physical-storage decision layered on top of the logical schema, not a replacement for good indexing; a well-chosen partition key reduces how much data a query has to consider, but you generally still need indexes within each partition for anything beyond the partition-pruning win itself.
Describe the main differences between OLTP and OLAP systems and how schema design changes for each. Using an e-commerce orders domain, explain how you would design the transactional (OLTP) schema and how you'd design the analytical (OLAP) schema. Discuss normalization, indexing, ETL/ELT patterns, query-latency expectations, and typical query types.
Sample Answer
Direct answer
OLTP systems are optimized for many small, concurrent transactions on current data, so their schemas are normalized to keep writes cheap and consistent; OLAP systems are optimized for large, read-only aggregations over historical data, so their schemas are denormalized (often star-schema-shaped) to keep scans and joins cheap.
Structured elaboration
| Dimension | OLTP | OLAP |
|---|---|---|
| Normalization | High (3NF+), minimizes update anomalies | Lower, denormalized for read speed |
| Query type | Point lookups, small transactional writes | Large aggregations, scans, group-bys |
| Query latency goal | Milliseconds | Seconds is often acceptable |
| Concurrency | Many concurrent short transactions | Fewer, heavier concurrent queries |
| Storage layout | Row-oriented, indexed for point access | Often columnar, indexed/partitioned for scans |
Worked example
For an e-commerce orders domain: the OLTP schema is customers, orders, order_items, payments, all normalized with foreign keys, so that placing an order is a small, fast transaction with ACID guarantees (atomicity, consistency, isolation, durability) touching only the rows involved and never risking an update anomaly on shared data. The OLAP schema built from the same domain, feeding a revenue dashboard, is typically a denormalized fact table like fact_order_line(date_key, customer_key, product_key, quantity, revenue) joined to small dimension tables, so that "total revenue by product category last quarter" is one scan and aggregation over a purpose-built table rather than a multi-way join across the live transactional tables (which would also risk slowing down the transactional workload itself).
Trade-offs and pitfalls
- Running analytical queries directly against the OLTP schema is the most common mistake this comparison is testing for: heavy scans compete for the same locks and buffer-pool space as live transactional writes, so most teams replicate or ETL the OLTP data into a separate OLAP store (a warehouse) rather than analyzing production directly.
- ETL/ELT is the bridge between the two: batch or change-data-capture (CDC) pipelines periodically transform the normalized OLTP shape into the denormalized OLAP shape, meaning the OLAP side is always somewhat stale relative to the OLTP source, by however long that pipeline's latency is.
- The typical enterprise reporting source of truth is the OLAP side, precisely because the OLTP schema is optimized for correctness-under-concurrency, not for the kind of ad hoc, multi-dimensional slicing that reporting needs.
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.