Advanced Data Modeling
Difficulty: Hard | Companies: Google, Amazon, Meta, Netflix, Uber
What a schema is really deciding
A data model is a set of bets about how the workload will behave. Grain, key design, and normalization level each encode an assumption: that analysts filter by date before product, that a handful of attributes change rarely, that one customer may hold many accounts, and that history must stay reconstructable when an audit asks what the numbers looked like in March. When those assumptions hold, the warehouse stays fast and independent reports agree with each other. When they fail, you get join fan-out, revenue counted twice, and a dashboard argument nobody can settle because both sides computed a correct answer to a different question. This lesson walks the major patterns â star and snowflake shapes, slowly changing dimensions, bridge tables, bi-temporal history, nested storage, data vault, and hierarchy representations â and attaches a decision rule to each so a design can be defended in review instead of merely inherited.
Star Schema Design
Begin with grain: one sentence stating what a single fact row means. One row per sale line item, per day, per store fixes the keys, decides which measures may be summed, and tells you which dimensions can be joined without changing an answer. Facts then fall into three families. Transaction facts record events and are fully additive. Periodic snapshot facts record a balance at a cut-off, so summing an account balance across days double-counts and the measure is only semi-additive. Snapshot facts record a state and are not additive at all. Skipping this classification produces the classic fan-out bug: a daily fact joined to a weekly dimension multiplies every measure by seven, and the inflated total looks plausible enough that nobody re-checks it.
-- Fact table
CREATE TABLE fact_sales (
sale_id BIGINT PRIMARY KEY,
date_key INT REFERENCES dim_date(date_key),
product_key INT REFERENCES dim_product(product_key),
customer_key INT REFERENCES dim_customer(customer_key),
store_key INT REFERENCES dim_store(store_key),
quantity INT,
unit_price DECIMAL(10,2),
discount_amount DECIMAL(10,2),
total_amount DECIMAL(10,2)
);
-- Dimension tables
CREATE TABLE dim_date (
date_key INT PRIMARY KEY,
full_date DATE,
year INT,
quarter INT,
month INT,
day_of_week INT,
week_number INT
);
CREATE TABLE dim_product (
product_key INT PRIMARY KEY,
product_id INT,
product_name VARCHAR(255),
category VARCHAR(100),
subcategory VARCHAR(100),
brand VARCHAR(100)
);
âšī¸
Key Insight: Star schema denormalizes dimension tables for query performance. Fact tables contain foreign keys to dimensions and measurable metrics. This structure is optimal for OLAP queries.
Snowflakeing normalizes the dimension: dim_product carries a category key, the category row carries a department key, and one department row is shared by every product beneath it. Storage drops and a renamed department is corrected in a single place instead of fifty thousand copies. The cost is one extra join per query, and because most BI tools regenerate star-shaped joins automatically, the storage saving rarely reaches the analyst in the form of speed. Normalize when attributes change independently of each other, when a hierarchy is shared by several facts, or when the same label appears so often that a typo would otherwise need a full table rewrite. Leave it flat when query latency dominates and the dimension holds under a million rows.
Snowflake Schema
-- Normalized dimensions
CREATE TABLE dim_product (
product_key INT PRIMARY KEY,
product_id INT,
product_name VARCHAR(255),
category_key INT REFERENCES dim_category(category_key),
brand_key INT REFERENCES dim_brand(brand_key)
);
CREATE TABLE dim_category (
category_key INT PRIMARY KEY,
category_name VARCHAR(100),
department_key INT REFERENCES dim_department(department_key)
);
CREATE TABLE dim_department (
department_key INT PRIMARY KEY,
department_name VARCHAR(100)
);
Slowly Changing Dimensions (SCD)
-- SCD Type 1: Overwrite
UPDATE dim_customer
SET city = 'San Francisco',
last_modified = CURRENT_TIMESTAMP
WHERE customer_id = 101;
-- SCD Type 2: Add new row
INSERT INTO dim_customer (
customer_id, customer_name, city,
effective_date, expiry_date, is_current
)
SELECT
customer_id, customer_name, 'San Francisco',
CURRENT_DATE, '9999-12-31', true
FROM dim_customer
WHERE customer_id = 101 AND is_current = true;
UPDATE dim_customer
SET expiry_date = CURRENT_DATE - 1,
is_current = false
WHERE customer_id = 101 AND is_current = true;
-- SCD Type 3: Add new column
ALTER TABLE dim_customer ADD COLUMN previous_city VARCHAR(100);
UPDATE dim_customer
SET previous_city = city,
city = 'San Francisco'
WHERE customer_id = 101;
Pick the type from the question the business is asking, not from habit. Type 1 answers what we believe now: overwrite the row, keep no history, and accept that the correction cannot be audited. Type 2 answers what did we believe then: insert a new version with an effective date and an expiry date, flip the current flag, and a report for March replays the values that were valid in March. That inflates the dimension â a customer with four address changes carries five rows â so every read must filter on the current flag or bind to a date, or revenue is counted once per version. Type 3 keeps the previous value in its own column: cheap, but a third change silently destroys the second. Decision rule: if a query in the last year needed last quarter's value, use Type 2; if the change fixes a typo, use Type 1.
Bridge Table for Many-to-Many
-- Many-to-many relationship
CREATE TABLE bridge_order_products (
order_id INT,
product_id INT,
quantity INT,
unit_price DECIMAL(10,2),
PRIMARY KEY (order_id, product_id)
);
-- Query with bridge table
SELECT
o.order_id,
p.product_name,
b.quantity,
b.unit_price,
b.quantity * b.unit_price AS line_total
FROM orders o
INNER JOIN bridge_order_products b ON o.order_id = b.order_id
INNER JOIN products p ON b.product_id = p.product_id;
A bridge is a fact-shaped table: it holds both foreign keys plus the quantity that belongs to the relationship rather than to either side. Order and product is the standard case â quantity and unit price live on the line, so reading them without the bridge would attribute one order's quantity to every product it contained. Two hazards follow. First, weights: if the model needs share of order, the bridge must carry a fraction that sums to exactly one per order, otherwise every ratio fed by it is inflated by the order size. Second, fan-out: joining one bridge to another multiplies row counts, so aggregate each side separately and join the aggregates instead of stacking the joins.
Temporal Data Model
-- Bi-temporal table
CREATE TABLE employee_history (
employee_id INT,
effective_date DATE,
expiry_date DATE,
as_of_date TIMESTAMP,
name VARCHAR(255),
department_id INT,
salary DECIMAL(10,2),
PRIMARY KEY (employee_id, effective_date, as_of_date)
);
-- Query point in time
SELECT *
FROM employee_history
WHERE employee_id = 101
AND effective_date <= '2024-06-15'
AND expiry_date > '2024-06-15'
AND as_of_date = (
SELECT MAX(as_of_date)
FROM employee_history
WHERE employee_id = 101
AND effective_date <= '2024-06-15'
);
Bi-temporal storage runs two clocks at once. The valid-time columns say when the fact was true in the world; the transaction-time column records when the row was loaded. Answering what salary the system believed on 15 June fixes as_of_date to the newest stamp at or before that day while the valid-time predicate selects the version in force. Drop the second clock and an August correction silently rewrites June's answer, which is exactly what an audit exists to catch. The primary key must include both clocks, and every read path needs an explicit as-of predicate: omit it and the query returns all versions at once, inflating totals by the number of revisions that were ever loaded.
BigQuery Denormalized Model
-- BigQuery nested and repeated fields
CREATE TABLE `project.dataset.orders` (
order_id INT64,
customer STRUCT<
customer_id INT64,
name STRING,
email STRING
>,
items ARRAY<STRUCT<
product_id INT64,
product_name STRING,
quantity INT64,
price NUMERIC
>>,
order_date TIMESTAMP
);
-- Query nested fields
SELECT
order_id,
customer.name,
item.product_name,
item.quantity
FROM `project.dataset.orders`,
UNNEST(items) AS item
WHERE customer.name LIKE '%Smith%';
Nesting trades joins for scan volume. Carrying the items array inside the order row lets one scan read an entire order, which is why wide denormalized tables beat star schemas on dashboards that filter and aggregate in a single pass. The costs are concrete. Updating a customer's email rewrites every order row that embedded it, so volatile attributes never belong in the nested copy. Arrays grow past the recommended nesting depth when orders carry thousands of line items. And unnesting multiplies rows, so any aggregate must be computed per order before joining to dimensions, or one order with five items contributes five customers to a distinct count. Repeat stable attributes, keep volatile ones in a side table, and treat nesting depth as a budget you monitor rather than a limit you discover in production.
Data Vault Modeling
-- Hub: Business keys
CREATE TABLE hub_customer (
customer_hk CHAR(32) PRIMARY KEY,
customer_bk VARCHAR(100),
load_date TIMESTAMP,
record_source VARCHAR(100)
);
-- Link: Relationships
CREATE TABLE link_order_customer (
order_customer_hk CHAR(32) PRIMARY KEY,
order_hk CHAR(32),
customer_hk CHAR(32),
load_date TIMESTAMP,
record_source VARCHAR(100)
);
-- Satellite: Descriptive attributes
CREATE TABLE sat_customer_details (
customer_hk CHAR(32),
load_date TIMESTAMP,
load_end_date TIMESTAMP,
name VARCHAR(255),
email VARCHAR(255),
phone VARCHAR(50),
record_source VARCHAR(100)
);
Data vault separates structure from content. Hubs hold business keys and never change, links hold relationships, and satellites carry the attributes together with their load and end timestamps. Nothing is updated in place, so loads are append-only, concurrent feeds rarely block each other, and a late-arriving file can be replayed without rewriting history that downstream reports already consumed. The redundancy lands on the reader: every query assembles its answer from hub, link, and satellite joins, which makes a serving layer of marts mandatory rather than optional. Choose data vault for the integration zone of a warehouse fed by many systems whose keys disagree; choose star or snowflake for the layer analysts actually query, where a single scan should answer the question.
Graph Data Model
-- Nodes and edges for graph data
CREATE TABLE graph_nodes (
node_id VARCHAR(100) PRIMARY KEY,
node_type VARCHAR(50),
properties JSONB
);
CREATE TABLE graph_edges (
edge_id SERIAL PRIMARY KEY,
source_node VARCHAR(100),
target_node VARCHAR(100),
edge_type VARCHAR(50),
weight DECIMAL(10,4),
properties JSONB,
FOREIGN KEY (source_node) REFERENCES graph_nodes(node_id),
FOREIGN KEY (target_node) REFERENCES graph_nodes(node_id)
);
-- Query graph relationships
SELECT
n1.node_id AS source,
n2.node_id AS target,
e.edge_type,
e.weight
FROM graph_nodes n1
INNER JOIN graph_edges e ON n1.node_id = e.source_node
INNER JOIN graph_nodes n2 ON e.target_node = n2.node_id
WHERE n1.node_type = 'user'
AND n2.node_type = 'product';
The node-and-edge shape answers one-hop and two-hop questions with plain indexed joins, and the weight column lets you rank the paths you find. Traversal depth is where it breaks. A node with twenty neighbours exposes a million paths at depth five, and the planner has no way to predict that explosion before running it. Bound the recursion explicitly, keep an array of visited node ids to cut cycles, and inspect the row count per step while you tune the limit. Past roughly ten levels of traversal, or once the pattern set grows beyond a few fixed shapes, move the workload to a graph engine such as Neo4j, Amazon Neptune, or the Apache AGE extension on PostgreSQL, and keep the relational copy for reporting.
Materialized Path Pattern
-- Store hierarchy as path
CREATE TABLE categories (
id INT PRIMARY KEY,
name VARCHAR(100),
path TEXT, -- '/1/5/12/'
depth INT
);
-- Query all descendants
SELECT *
FROM categories
WHERE path LIKE '/1/5/%'
ORDER BY path;
-- Query ancestors
SELECT *
FROM categories
WHERE id IN (
SELECT UNNEST(STRING_TO_ARRAY('/1/5/12/', '/')::INT[])
WHERE UNNEST != ''
);
Adjacency List with Closure Table
-- Closure table for hierarchy
CREATE TABLE category_closure (
ancestor_id INT,
descendant_id INT,
depth INT,
PRIMARY KEY (ancestor_id, descendant_id)
);
-- Query descendants
SELECT c.*
FROM categories c
INNER JOIN category_closure cc ON c.id = cc.descendant_id
WHERE cc.ancestor_id = 5;
-- Query ancestors
SELECT c.*
FROM categories c
INNER JOIN category_closure cc ON c.id = cc.ancestor_id
WHERE cc.descendant_id = 12;
Materialized path stores ancestry as a string, so descendants become a prefix scan: index-friendly, cheap to read, and trivial to serialize over an API. Ancestors require splitting the path, which is awkward but workable. The weakness is maintenance â renaming a subtree rewrites every descendant's path string, and no foreign key can validate the format you chose. The closure table precomputes every ancestor-descendant pair with a depth, so both directions become one indexed join, at the cost of roughly nodes multiplied by average depth rows. Choose path for static, read-heavy hierarchies you expose over HTTP; choose closure when you query both directions, move nodes often, or need depth without string parsing.
Choosing a pattern under pressure
Rather than memorizing DDL, walk these questions in order â each answer changes a statement you would otherwise have to migrate later.
| Situation | Pattern to reach for | What it protects |
|---|---|---|
| A measure must be correct across a date range | Periodic snapshot fact on a date dimension | Semi-additive totals that do not double-count |
| An attribute changes and last quarter must stay reportable | SCD Type 2 with effective and expiry dates | History, at the price of row growth |
| A relationship carries its own quantities | Bridge table whose weights sum to one | Line-level accuracy without fan-out |
| Several source systems disagree on the same key | Data vault hub plus survivorship satellite | One surviving record per real entity |
| Subtrees are read constantly and rarely move | Materialized path | Fast descendant reads with minimal storage |
| Traversals exceed five hops in either direction | Closure table or a graph engine | Bounded, predictable query plans |
Follow-Up Questions
- When would you choose star schema over snowflake schema?
- How do you handle many-to-many relationships in a star schema?
- Explain the trade-offs between SCD Type 1, 2, and 3.
- How would you design a data model for real-time analytics?
- What's the best approach for modeling hierarchical data?
- How do you handle schema evolution in a data warehouse?
Common Mistakes
Summing a semi-additive measure across the time dimension
Fix: Keep balances in a periodic snapshot fact and add only across the non-time axis
Joining a fact to a dimension at the wrong grain and trusting the inflated total
Fix: Assert the row count after every join and aggregate back to the fact grain before comparing
Reading an SCD Type 2 dimension without a date predicate
Fix: Filter on the current flag or bind the report to an as-of date before any measure is aggregated
Best Practices
- State the grain of every fact table in a comment and enforce it in design review
- Add a row-count and checksum assertion after each join in the pipeline that feeds a mart
- Keep volatile attributes out of nested or denormalized storage and reference them instead
- Record load timestamps in every hub and satellite so a replay is auditable
- Choose hierarchy storage from query direction before writing the first DDL statement
Interview Questions
Q1: Star schema or snowflake schema?
Star for query speed with flat dimensions; snowflake when hierarchies are shared across facts or attributes change independently and must stay consistent
Q2: Which slowly changing dimension type keeps full history?
Type 2, which inserts a new row with effective and expiry dates and marks exactly one version as current
Q3: How do you prevent fan-out when a fact joins several dimensions?
Join only keys that are unique on the dimension side, then aggregate back to the fact grain before summing measures
Q4: When would you choose data vault over a star schema?
In the integration zone fed by many systems, where append-only hubs, links, and satellites absorb conflicts a star cannot represent
Key Takeaways
- Fix the grain of a fact table first; every key and measure follows from that one sentence
- Semi-additive measures cannot be summed across time, so snapshot facts own the date axis
- Slowly changing dimension type is a reporting question, not a storage preference
- Bridge tables need weights that sum to one or every ratio they feed is inflated
- Hierarchy storage follows query direction: prefix reads want paths, two-way reads want closure