Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 58/ 160
03. Joins & Relational Querying

Querying Star Schemas (Joining Fact Tables to Multiple Dimension Tables)

Query facts with many dimensions while watching for fan-out and filter placement.

IntermediateFact Table · Dimensions3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Take the big list of sales, look up the details for each sale, then group and add up.

Think of it like…

A shop's till roll surrounded by reference books: each receipt line says "product 48, store 3, day 1,203, ₹499", and you look up product 48, store 3 and day 1,203 in their books to group the receipts into "shoes in Pune in November".

Where you’ve seen it

SELECT d.year_month, p.category, SUM(f.revenue) AS revenue FROM fact_sales f JOIN dim_date d ON d.date_key = f.date_key JOIN dim_product p ON p.product_key = f.product_key JOIN dim_store s ON s.store_key = f.store_key WHERE d.year = 2026 AND s.state = 'Maharashtra' GROUP BY d.year_month, p.category ORDER BY 1, 3 DESC;

Words you’ll hear

Fact table
Measures (revenue, quantity) at a fixed grain, with a foreign key to each dimension.
Dimension table
Descriptive attributes used to filter and group: product category, store city, month.
Role-playing dimension
One dimension used for several roles, such as dim_date for order date and ship date.
Drill-across
Combining two fact tables by aggregating each to shared dimensions first.

Visual diagram

Loading interactive diagram

Theory & example queries

The shape of a star query

Each dimension join is many-to-one (many fact rows, one dimension row per key), so joining dimensions never changes the number of fact rows, and SUMs stay correct. Filters go on dimension attributes (d.year = 2026, s.state = 'Maharashtra'), GROUP BY uses dimension attributes, and only measures are aggregated. Warehouses optimise exactly this shape: they filter the small dimensions first and push the matching keys down into the fact scan to skip partitions and blocks.

When a dimension plays two roles, join it twice under different aliases: JOIN dim_date od ON od.date_key = f.order_date_key JOIN dim_date sd ON sd.date_key = f.ship_date_key. If facts can arrive before their dimension row exists, well-built warehouses point them at an "unknown" member (key -1) rather than leaving the key NULL, so inner joins don't silently drop revenue.

Average days to ship by month orderedQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  od.year_month,3  AVG(sd.full_date - od.full_date) AS avg_days_to_ship4FROM5  fact_orders f6  JOIN dim_date od ON od.date_key = f.order_date_key7  JOIN dim_date sd ON sd.date_key = f.ship_date_key8GROUP BY9  od.year_month10ORDER BY11  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative monthly shipping times3 sample rows
Representative monthly shipping times
year_monthavg_days_to_ship
2026-012.5
2026-021.8
2026-033.2

Note: Sample averages assume valid order- and ship-date dimension rows and use illustrative delivery intervals. AVG of integer date differences is typically returned with numeric precision.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Filter and group by dimensions, sum fact measures, alias role-playing dimensions.

Pitfalls: two facts, history and non-additive measures

Never join two fact tables to each other on shared dimension keys: sales and returns both have many rows per product per day, so the join multiplies them. Drill across instead: aggregate each fact to the same dimensions (product, month) in its own CTE, then join the summaries. That's why shared, "conformed" dimensions matter.

With slowly changing dimensions (type 2), each version of a customer has its own surrogate key, so joining on the fact's key reports each sale with the customer's attributes at the time of sale. To group by today's attributes, join through the natural key to the row where is_current is true. And watch measure types: revenue is additive across all dimensions, but an account balance or stock level is semi-additive, so sum it across accounts but take the last value across time.

Sales vs returns by product and monthQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  s AS (3    SELECT4      product_key,5      date_key / 100 AS ym,6      SUM(revenue) AS sales7    FROM8      fact_sales9    GROUP BY10      1,11      212  ),13  r AS (14    SELECT15      product_key,16      date_key / 100 AS ym,17      SUM(refund) AS returns18    FROM19      fact_returns20    GROUP BY21      1,22      223  )24SELECT25  s.product_key,26  s.ym,27  s.sales,28  COALESCE(r.returns, 0) AS returns29FROM30  s31  LEFT JOIN r USING (product_key, ym);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/31
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative sales and returns3 sample rows
Representative sales and returns
product_keyymsalesreturns
412026111250004200
56202611985000
412026101130003100

Note: Sample data uses integer division to produce yyyymm month keys and assumes product 56 had no returns in November. COALESCE shows 0 only when no matching return aggregate exists.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

(date_key here is a yyyymmdd integer.)

Key takeaway: Drill across with pre-aggregated facts; mind SCD versions and semi-additive measures.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Question

Pick the fact table

Find the fact whose grain and measures answer the question: revenue lives in fact_sales at order-line grain.

SQL at this step
1FROM2  fact_sales f
What to watch at this step
Grain
one row per order line
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A star query joins a central fact table (one row per sale, click or shipment, with numeric measures) to the dimension tables around it (date, customer, product, store) on their surrogate keys, filters on dimension attributes, groups by dimension attributes and sums the measures. "Revenue by product category per month in 2026 for stores in Maharashtra" is one fact table joined to three dimensions.

Why it matters: Almost every BI dashboard and analytics question runs against a star schema, so analysts and data engineers write these queries daily. Interviews test whether you join on the right keys, keep the fact table's grain, handle dimensions that play more than one role (order date and ship date), and avoid joining two fact tables directly.

When to reach for it

  • Dashboards and BI reports over a warehouse
  • Ad-hoc analysis by date, product, customer or region
  • Comparing business processes through shared dimensions

When to avoid or be careful

  • Joining two fact tables on dimension keys
  • Summing semi-additive measures like balances across dates
  • Filtering on fact columns that duplicate dimension attributes

Ways to combine facts and dimensions

Fact joined to dimensions
Best for: Standard BI questions

Strengths: Many-to-one joins keep totals correct; warehouses optimise it.

Watch out: Needs clean surrogate keys and unknown members.

Drill-across (aggregate each fact, then join)
Best for: Comparing two processes, such as sales and returns

Strengths: No fan-out between facts.

Watch out: Needs conformed dimensions and an extra step.

Fact joined directly to fact
Best for: Rarely, only on a shared degenerate key like order_id

Strengths: Simple to write.

Watch out: Multiplies rows when either side has many rows per key.

Interview signals & numbers to know

When this topic comes up

  • “Revenue by category and month for one region”
  • “Compare sales and returns per product”
  • Order date vs ship date
  • Fact and dimension tables
  • BI dashboard queries

Benchmarks & rules of thumb

many-to-one -
every fact-to-dimension join
-1 -
a common key for the unknown dimension member
2 aliases -
for a dimension used in two roles

Common mistakes & follow-ups

Common interview mistakes

  • Joining fact_sales to fact_returns on product_key and date_key, inflating both totals.
  • Grouping by customer attributes from the current row when the question asks about attributes at the time of sale, or the reverse.
  • Summing daily account balances across a month and reporting it as the month's balance.

Likely interviewer follow-ups

  • How would you report sales and returns side by side per product?
  • How do you join dim_date for both order date and ship date?
  • What's a semi-additive measure, and how do you aggregate it?
Interview tip: Narrate it as "fact for the measure, dimensions for the filters and groups". Then mention drill-across for two facts, which shows you've worked with real warehouses.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Querying Star Schemas (Joining Fact Tables to Multiple Dimension Tables) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Combining Joins with Aggregations Safely
Next topic
Deduplicating Rows Using Self Joins