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.
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.
You're storing semi-structured product metadata. Discuss the pros and cons of using a JSON column in PostgreSQL versus fully normalizing the attributes into relational columns and tables. Address queryability, indexing, schema evolution, and storage.
Sample Answer
Direct answer
For semi-structured product metadata, a JSON column is the better default when attributes vary heavily by category and change often, while fully normalizing into relational columns is better when the same handful of attributes are shared across most products and need to be reliably filterable and indexable; most real catalogs land on a hybrid of both.
Structured elaboration
- Queryability: normalized columns support efficient, indexable equality and range filters natively (
WHERE color = 'red' AND size = 'M'); a JSON column requires either JSON-path query syntax (slower without a specific index) or extracting fields at query time. - Indexing: normalized columns get ordinary B-tree indexes; a JSONB column can be indexed too (a GIN index in Postgres supports efficient containment queries), but indexing a JSON column is coarser-grained and generally less efficient than a dedicated column index for a specific, stable, frequently-filtered attribute.
- Schema evolution: a JSON column absorbs a new, category-specific attribute with zero migration; adding a new relational column for every possible category-specific attribute (battery_capacity for electronics, screen_size for a different category) leads to a very wide table full of NULLs for products where that attribute doesn't apply.
- Storage: JSONB is reasonably compact and the values are stored parsed (unlike plain
JSON, which stores raw text), but a value repeated across many rows (a common category name, say) isn't as compactly stored or as easy to enforce consistency on as a normalized lookup table with a foreign key.
Worked example
For semi-structured event data specifically (a related but distinct case), there are three concrete strategies worth naming: (1) store the raw JSON and use JSON path functions at query time, maximum flexibility, worst per-query performance since nothing is pre-extracted; (2) flatten into a wide table with one column per known field, best query performance but a schema migration every time a new field appears; (3) extract only the frequently-queried fields into real columns while leaving the rest in a JSON "overflow" column, a middle ground that captures most of the performance benefit for the fields that matter without requiring a migration for every rarely-used field.
Trade-offs and pitfalls
- The most common mistake is treating this as an all-or-nothing decision; the practical pattern for a product catalog is a hybrid: normalize the small set of attributes shared across (nearly) all products and used for cross-category filtering (price, name, category_id), and keep a
attributes JSONBcolumn for the long tail of category-specific fields. - Indexing a JSONB column with a GIN index supports containment queries (
attributes @> '{"color":"red"}') reasonably well, but composite filters across multiple JSON keys plus a normalized column don't optimize as cleanly as an equivalent all-relational composite index; if a specific JSON field turns out to be extremely commonly filtered, promoting it to its own indexed column (even while keeping the rest in JSON) is usually worth the one-time migration. - Schema evolution for the JSON side still needs discipline even without a database migration: a convention for field naming, a shared understanding of which fields are required per category, and ideally a validation layer (a JSON schema check at write time) to prevent the same logical attribute from being spelled two different ways across different writers.
Explain polyglot persistence and when it makes sense to use multiple specialized databases (relational, document, and graph) within a single product. Provide an example architecture for an e-commerce platform that uses each type, and describe patterns to keep data consistent across the different stores (change data capture, an event bus, or best-effort eventual consistency).
Sample Answer
Direct answer
Polyglot persistence means deliberately using more than one specialized database within a single product, each chosen for the specific access pattern it serves best, rather than forcing every workload onto one general-purpose store; it makes sense once a single workload (search, graph traversal, time-series, transactional) is important and distinct enough that a specialized store's advantage clearly outweighs the operational cost of running an additional system.
Structured elaboration
For an e-commerce platform, a realistic polyglot architecture: a relational database (Postgres) as the transactional system of record for orders, payments, and inventory, where ACID guarantees matter most; a document or search store (Elasticsearch) for product search and faceted browsing, where full-text relevance ranking and flexible filtering matter most and eventual consistency with the relational source is acceptable; and a graph database (Neo4j or similar) for a "customers who bought this also bought" recommendation feature, where multi-hop relationship traversal is the dominant query shape relational joins handle poorly at depth.
Keeping data consistent across these stores: change data capture (CDC, streaming database changes from the relational source of truth into the other stores' update pipelines) is the most common pattern, since it derives the secondary stores from the primary without requiring the application to remember to dual-write everywhere; an event bus (the application publishes domain events that each interested store's own consumer subscribes to) is a similar pattern at the application layer instead of the database layer; and best-effort eventual consistency is simply the accepted state for the search/recommendation stores, which are allowed to lag the transactional source by seconds to minutes without breaking correctness for their use case.
Worked example
Concretely: when an order is placed and inventory decrements in Postgres, a CDC stream picks up that change and updates the product's "in stock" facet in Elasticsearch within a few seconds; a shopper searching for that product during that short window might see a slightly stale stock count, which is an acceptable trade-off for search, but would never be acceptable for the actual checkout flow itself, which always reads current inventory directly from Postgres, not from the search index.
Trade-offs and pitfalls
- The operational cost is real and compounding: each additional specialized store is another system to provision, monitor, upgrade, and staff expertise for, and every additional store also means another potential point of data divergence to detect and reconcile.
- The most common mistake is reaching for polyglot persistence prematurely, adding a specialized store for a workload that a well-indexed relational table would have handled adequately; the decision should follow from measured pain (search relevance genuinely suffering, or graph queries genuinely timing out on relational joins), not from a general belief that specialized stores are always better for their named use case.
- Whichever consistency-propagation mechanism you choose (CDC or an event bus), you need an explicit answer for what happens when propagation fails or lags unacceptably; without a monitored lag metric and a defined "acceptable staleness" bound per secondary store, drift accumulates silently until a user-visible inconsistency finally surfaces it.
Describe how to model one-to-many and many-to-many relationships in a relational database and in a document-oriented NoSQL store such as MongoDB. Provide short schema sketches for both and explain how read and write access patterns influence whether you embed related data or reference it.
Sample Answer
Direct answer
One-to-many and many-to-many relationships look structurally similar in a relational database (a foreign key, or a junction table) and in a document store (an embedded array, or a reference plus a separate collection); the deciding factor in the document case is whether the related data is read together with its parent and rarely updated independently (embed) or shared/updated across many parents (reference).
Structured elaboration
Relational: one-to-many via a foreign key on the "many" side (comments.post_id -> posts.post_id); many-to-many via a junction table (post_tags(post_id, tag_id)).
Document store (e.g., MongoDB): the same two relationships have two representations each, and the choice is an access-pattern decision, not a structural requirement:
- Embed: nest the related data directly inside the parent document. Good when the child is always read alongside the parent, is bounded in size, and is rarely updated independently of the parent (a blog post embedding its first few comments for a fast initial render).
- Reference: store the child in its own collection and reference it by ID, similar to a relational foreign key. Good when the child is large, unbounded (could grow without limit), shared across multiple parents, or updated far more often than the parent (a
commentscollection referencingpost_id, since a popular post could have unbounded comments that would blow past a document's practical size if embedded).
Worked example
// Embedded one-to-many: a post carries a small, bounded list of tags directly
{ post_id: "p1", title: "...", tags: ["postgres", "schema-design"] }
// Referenced one-to-many: comments live in their own collection, referencing the post
{ comment_id: "c1", post_id: "p1", body: "..." } // in a separate `comments` collection
// Referenced many-to-many: a post referencing multiple category ids, and vice versa
{ post_id: "p1", category_ids: ["cat_1", "cat_2"] }
{ category_id: "cat_1", name: "Databases" }
The read/write pattern decides the choice: tags are embedded because they're small, bounded, and always shown with the post; comments are referenced because a post's comment count is unbounded and comments are frequently written independently of the post itself (a new comment shouldn't require rewriting the whole post document).
Trade-offs and pitfalls
- Embedding an unbounded child collection (comments, order line items on a growing cart) risks hitting the document size limit and, even before that limit, makes every unrelated update to the parent rewrite an ever-larger document.
- Referencing everything defeats the main performance benefit of a document store (fetching a whole aggregate in one read) by turning every parent-with-children read into multiple round trips, which is exactly the "join cost" a document database was chosen to avoid in the first place.
- Most production document schemas land on a hybrid: embed the stable, small, always-needed subset (the first N comments, or a denormalized comment count) and reference the full, unbounded collection separately, giving fast common-case reads without hitting the growth and independent-update problems of full embedding.
Describe how to model one-to-one, one-to-many, and many-to-many relationships in a relational schema. Provide example table shapes (table names, key columns) for each relationship and explain how to enforce cardinality and referential integrity. Cover optional versus mandatory relationships and how you would enforce them in SQL.
Sample Answer
Direct answer
One-to-one, one-to-many, and many-to-many are the three cardinalities a relationship can have, and each maps to a different physical structure: 1:1 usually merges into one table or splits with a shared key, 1:N puts a foreign key on the "many" side, and N:M requires a separate junction table.
Structured elaboration
- One-to-one: each row in A relates to at most one row in B and vice versa. Model it either by merging the columns into a single table (most common, when B's columns are rarely queried separately) or by giving B a primary key that is also a foreign key referencing A (
user_idis both PK and FK onuser_profile), which naturally enforces the 1:1 cardinality without an extra unique constraint. - One-to-many: each row in A relates to many rows in B, but each row in B relates to at most one row in A. Model it by placing a foreign key on the "many" side (B):
orders.customer_id -> customers.customer_id. - Many-to-many: rows on both sides can relate to many rows on the other. This cannot be represented with a single foreign key; it requires a junction (associative) table holding a foreign key to each side, with the pair typically forming the composite primary key:
enrollments(student_id FK, course_id FK, PRIMARY KEY(student_id, course_id)).
Optional vs mandatory participation changes nullability and constraints, independent of the cardinality itself:
- Mandatory: the foreign-key column is
NOT NULL(every order must have a customer). - Optional: the foreign-key column is nullable, or the relationship lives only in the junction table so absence of a row is the "optional" state (a student with zero enrollments simply has no rows in
enrollments).
Worked example
-- One-to-one: user and their profile, using a shared primary key
CREATE TABLE users (user_id INT PRIMARY KEY, email TEXT NOT NULL UNIQUE);
CREATE TABLE user_profile (
user_id INT PRIMARY KEY REFERENCES users(user_id),
bio TEXT,
avatar_url TEXT
);
-- One-to-many: customer to orders (mandatory customer, so NOT NULL)
CREATE TABLE customers (customer_id INT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL REFERENCES customers(customer_id),
placed_at TIMESTAMP NOT NULL
);
-- Many-to-many: students and courses, via a junction table
CREATE TABLE students (student_id INT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE courses (course_id INT PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE enrollments (
student_id INT NOT NULL REFERENCES students(student_id),
course_id INT NOT NULL REFERENCES courses(course_id),
enrolled_on DATE NOT NULL,
PRIMARY KEY (student_id, course_id)
);
Cardinality is enforced structurally: user_profile.user_id being both the primary key and a foreign key makes it physically impossible to attach two profiles to one user. The composite primary key on enrollments makes it impossible to enroll the same student in the same course twice, while still allowing a student to enroll in many courses and a course to have many students.
Trade-offs and pitfalls
- The most common modeling mistake is trying to represent a many-to-many relationship with a single foreign key (or worse, a comma-separated list of IDs in one column); neither preserves referential integrity or supports efficient queries in either direction.
- For one-to-one, merging into a single table is usually right unless B's columns are large, rarely accessed, or access-controlled separately (e.g., splitting sensitive PII into its own table with tighter permissions is a legitimate reason to keep the 1:1 as two tables rather than one).
- Optional participation modeled as a nullable foreign key column can silently allow "orphan-looking" rows that pass a naive
NOT NULLcheck but still need application logic to decide what a NULL relationship means; document that meaning explicitly rather than leaving it implicit.
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.