Skip to main content

Data Modeling Interview Questions and Answers


Prepare for data engineering interviews with practical explanations of dimensional modeling, star and snowflake schemas, SCD Type 2, late-arriving data, many-to-many relationships, fact table grain, and denormalization.

How to use this guide: Start with the concise interview answer, walk through the example, and explain the tradeoffs. Real interviewers want to hear how you would apply the concepts, not just definitions.

1. How would you design a dimensional model for an e-commerce business?

Interview answer: Begin with the business processes and analytical questions, not the table names. For e-commerce, typical processes are order placement, payment, shipment, return, and inventory snapshots. Define a separate fact table at the appropriate grain for each process and connect it to conformed dimensions.

Example dimensional model

TableGrainExample columns
fact_order_lineOne line item on an orderorder_id, line_id, customer_key, product_key, order_date_key, quantity, net_sales
fact_paymentOne payment transactionpayment_id, order_id, payment_date_key, amount, status
fact_inventory_dailyOne product-location-day snapshotproduct_key, warehouse_key, date_key, on_hand_qty
dim_customerOne customer versioncustomer_key, customer_id, segment, city, effective dates
dim_productOne product versionproduct_key, sku, category, brand
dim_dateOne calendar datedate_key, month, quarter, year
-- Revenue by product category (order-line grain)
SELECT p.category, SUM(f.net_sales) AS revenue
FROM fact_order_line AS f
JOIN dim_product AS p ON f.product_key = p.product_key
GROUP BY p.category;
What interviewers look for: Clear grain, additive measures, surrogate keys, shared dimensions, handling of refunds, historical attributes, and no accidental double counting when combining order and payment facts.

2. What is the difference between a fact table and a dimension table?

Interview answer: A fact table records measurable business events or states at a declared grain. A dimension table provides descriptive context used to filter, group, and label those facts.

AspectFact tableDimension table
PurposeMeasures and business activityBusiness descriptions and attributes
Examplesquantity, revenue, balanceproduct category, customer segment
Typical keysForeign keys to dimensions; event identifiersSurrogate primary key; business key
GrowthOften high-volumeUsually smaller, but not always

Facts may be additive (sales amount across all dimensions), semi-additive (account balance across customers but not time), or non-additive (ratios such as conversion rate).

Nuance: Not every fact table has numeric measures. A factless fact table can capture an event or relationship, such as attendance or eligibility.

3. When would you choose a star schema over a snowflake schema?

Interview answer: Choose a star schema when analyst usability, simpler joins, and predictable reporting are primary goals. Consider a snowflake schema when dimension hierarchies need normalized management, are reused independently, or governance benefits outweigh query complexity.

CriteriaStar schemaSnowflake schema
DimensionsDenormalizedNormalized into related tables
JoinsUsually fewerUsually more
Ease of useOften simpler for BIMore complex navigation
RedundancyMore repeated attributesLess repeated hierarchy data

Example: In a star schema, dim_product contains SKU, category, and department. In a snowflake schema, category and department might be stored in separate dimension tables linked to product.

Interview tip: Do not claim star schemas are always faster. Modern optimizers, table sizes, clustering, caching, and workload patterns determine real performance. Benchmark representative queries.

4. How would you implement SCD Type 2?

Interview answer: Slowly Changing Dimension Type 2 preserves historical versions of tracked attributes. Use a surrogate key for each version, a stable business key, validity dates, and a current-row indicator. When tracked values change, close the old version and insert a new one.

Example history

customer_keycustomer_idcityvalid_fromvalid_tocurrent
101C1Pune2025-01-012026-03-01False
205C1Bengaluru2026-03-01NULLTrue

Use half-open validity intervals: valid_from <= event_time and event_time < valid_to (or an open-ended NULL).

-- Step 1: expire changed current versions (illustrative)
UPDATE dim_customer AS d
SET valid_to = :change_time, is_current = FALSE
FROM staged_customer AS s
WHERE d.customer_id = s.customer_id
  AND d.is_current = TRUE
  AND d.city IS DISTINCT FROM s.city;

-- Step 2: insert new and changed versions.
-- Compare staging to current versions and insert rows
-- where no matching current version exists.

In production, the expire-and-insert operations must be coordinated transactionally or through a warehouse-specific atomic strategy. Use NULL-safe comparisons, deterministic change ordering, and a uniqueness test for one current row per business key.

Interview tip: Discuss historical backfills, out-of-order CDC events, surrogate-key generation, and the difference between business effective time and ingestion time.

5. How do you handle late-arriving facts and dimensions?

Interview answer: Distinguish late facts (an event arrives after its business timestamp) from late dimensions (the descriptive entity arrives after the fact). Keep both event time and processing time, and make reprocessing possible.

Late-arriving facts

Load the fact into the correct historical date or partition based on event time. Recompute affected aggregates or partitions when required, using an overlap window and idempotent merges.

Late-arriving dimensions

One approach is to create an inferred dimension member with the known business key and placeholder attributes. Later, enrich it when the full dimension arrives. Another approach is to quarantine the fact until dimension resolution; the right choice depends on freshness and completeness requirements.

-- Resolve the customer version valid when the order occurred
SELECT f.order_id, d.customer_key
FROM staging_orders AS f
LEFT JOIN dim_customer AS d
  ON f.customer_id = d.customer_id
 AND f.order_ts >= d.valid_from
 AND (f.order_ts < d.valid_to OR d.valid_to IS NULL);
Important: A Type 2 dimension may need historical corrections when late changes arrive. A simple current-row lookup is not enough for point-in-time accuracy. Ensure validity intervals do not overlap.

6. How would you model many-to-many relationships?

Interview answer: Use a bridge table when a dimension member can relate to multiple members of another dimension, such as an account having multiple owners or a product belonging to multiple tags.

Example: Orders and promotions

TableRelevant columns
fact_orderorder_key, net_sales
dim_promotionpromotion_key, promotion_name
bridge_order_promotionorder_key, promotion_key, allocation_weight
-- Allocate sales across multiple promotions
SELECT p.promotion_name,
       SUM(f.net_sales * b.allocation_weight) AS attributed_sales
FROM fact_order AS f
JOIN bridge_order_promotion AS b
  ON f.order_key = b.order_key
JOIN dim_promotion AS p
  ON b.promotion_key = p.promotion_key
GROUP BY p.promotion_name;

If a $100 order has two promotions and both receive full credit, summing by promotion yields $200 of attributed revenue. Allocation weights, such as 0.5 and 0.5, can avoid double counting when the business requires allocated totals.

Interview tip: State the bridge grain, whether links are time-dependent, and whether the business wants full attribution or allocated attribution.

7. How do you choose the grain of a fact table?

Interview answer: The grain states exactly what one row represents. Declare it before choosing measures and foreign keys. The grain must support the required analytical questions without ambiguous duplication.

Three common fact table patterns

PatternExample grainUse case
Transaction factOne order lineSales and product analysis
Periodic snapshotOne product per warehouse per dayInventory balance trends
Accumulating snapshotOne order fulfillment lifecycleTracking ordered, packed, shipped, delivered milestones

For an order-line fact, quantity and line_revenue belong naturally at line grain. A header-level shipping charge should not be repeated on every line without an allocation rule, or it will be overcounted.

Interview tip: A strong answer starts with: “One row in this table represents…” Then explain dimensions, measures, and how updates or corrections are handled.

8. When would you denormalize a data model?

Interview answer: Denormalize when read performance, analyst usability, or reduced join complexity provides more value than strict normalization. Common examples include a reporting star schema, precomputed aggregates, and a wide table for frequently accessed dashboard attributes.

Benefits and tradeoffs

BenefitsCosts
Fewer joins for consumersData duplication and storage overhead
Simpler reporting queriesMore complex update and consistency logic
Precomputed metrics may improve latencyRefresh cost and possible stale results

Example: A dashboard repeatedly joins an order fact with product, category, and brand metadata. A denormalized product dimension or materialized reporting table may simplify queries and reduce repeated work.

Guardrail: Denormalization is not a substitute for correct grain. Avoid duplicating measures across one-to-many joins, and document refresh logic, ownership, and consistency guarantees.
Interview tip: Explain what you would measure: query latency, scanned bytes, concurrency, maintenance effort, freshness, and total cost of ownership.

Quick Revision: Interview Flashcards

What is a fact table's grain?

The precise meaning of one row, such as one order line or one product-warehouse-day snapshot.

Why use surrogate keys in SCD Type 2?

To distinguish multiple historical versions of the same business entity and link facts to the correct version.

What is a conformed dimension?

A shared dimension with consistent meaning and attributes across multiple business processes or fact tables.

What causes double counting?

Joining measures across incompatible grains or one-to-many relationships without aggregation or allocation rules.

What is an inferred dimension member?

A placeholder dimension row created when a fact arrives before the full dimension details are available.

What is a factless fact table?

A fact table that captures an event or relationship without a numeric measure, such as attendance or eligibility.

Hands-On Design Challenge

Scenario: An e-commerce platform processes orders, payments, shipments, refunds, and customer address changes. Design a dimensional model that supports daily revenue, repeat-customer analysis, historical city-level reporting, and refund rates. Define the grain of every fact, shared dimensions, SCD Type 2 rules, and how you would prevent double counting.

Key Takeaways

  • Declare the grain before designing the fact table.
  • Model each business process at its natural level of detail.
  • Use dimensions for descriptive context and facts for events or states.
  • Choose star or snowflake structures based on usability, governance, and measured performance.
  • Handle historical versions and late arrivals with explicit time semantics.
  • Use bridges and allocation rules for many-to-many relationships.
  • Denormalize intentionally, with clear consistency and maintenance tradeoffs.

SQL examples are illustrative and may need adjustments for PostgreSQL, Snowflake, BigQuery, SQL Server, or other databases. Validate historical joins and SCD implementation against your platform's supported syntax and transaction behavior.

Comments

Popular posts from this blog

How to migrate the data between AWS and Google Cloud Platform

There are several ways to migrate data between Amazon Web Services (AWS) and Google Cloud Platform (GCP). Here are three common approaches: Use a Cloud Data Integration Tool: Both AWS and GCP offer a range of tools that can help you move data between the two platforms. For example, AWS Data Pipeline is a fully-managed data integration service that can extract data from various sources, transform the data as needed, and load the data into a destination system. On GCP, Cloud Data Fusion is a similar tool that can help you build, execute, and monitor data pipelines between various data sources and destinations. You can use these tools to create a data pipeline that moves data between AWS and GCP. Use a Command-Line Tool: Another option is to use a command-line tool, such as aws s3 cp or gsutil, to transfer data between AWS S3 and GCP Cloud Storage. For example, you can use aws s3 cp to copy data from an S3 bucket to your local machine, and then use gsutil cp to upload the data to Cloud ...

Difference between Union and Union All in SQL

You might be using Union or Union All in your SQL code while doing Data Analysis or building Data Pipelines. Ever wondered what is the difference between them and how using one over another can be more efficient? Yes, there is a small yet significant difference between Union and Union All. Let's look at that by understanding each of them individually. 1. Union All  Union All basically allows you to concatenate the table that has a similar structure of tables. The important condition to have Union All of the tables is that both the tables should have the same number of columns. So when you take Union All of two tables what it does in the background is it directly joins the tables without removing duplicates or redundant records.   2. Union  Union is also similar to Union All except one difference that it removes the duplicates records before taking the Union of the tables.  There is one disadvantage of Union over Union All, that since it removes duplicated records bef...

What is Shuffling in Spark

Shuffling in Spark is a mechanism that Re-Distributes the data across different executors or workers in the clusters.  Why do we need to Re-Distribute the data?    A) Re-Distribution is needed when there is a need of increasing or decreasing the data partitions in the situations below: When the partitions are not sufficient enough to process the data load in the cluster When the partitions are too high in numbers that it creates task scheduling overhead and it becomes the bottleneck in the processing time. Re-Distribution can also be achieved by executing the shuffling on existing distributed data collection like RDD, DataFrames, etc by using the "Repartition" and "Coalesce" APIs in Spark. B) During Aggregation and Joins on data collection in Spark, all the data records belonging to aggregation or join should reside in the single partition and when the existing partitioning scheme doesn't satisfy this condition there is a need to re-distributing the data in in...