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 160/ 160
08. Transactions, Security & Production SQL Administration

Capstone Project: Designing, Optimizing & Querying a Full E-Commerce & SaaS Analytics Warehouse

Design schemas, load facts, optimize queries, and answer SaaS/e-commerce metrics end-to-end.

AdvancedSchema · Metrics · Tuning3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Design the tables, copy them into a reporting database, write the important business numbers, and check they're fast and correct.

Think of it like…

Building a small house rather than practising each trade separately: the foundation (schema), the frame (warehouse model), the wiring (metrics) and the inspection (tests) all have to fit, and mistakes in one show up in the others.

Where you’ve seen it

The leadership dashboard needs, every morning: net revenue by month (sales minus refunds), average order value, new vs returning revenue, the top 3 products in each category, Pro MRR with new, expansion, contraction and churn, and 90-day repeat rates by first-order month. All of it must reconcile with the payments provider's totals to the rupee.

Words you’ll hear

Fact grain
fct_order_items: one row per order line; fct_subscription_months: one row per subscription per month.
Conformed dimensions
dim_customer, dim_product and dim_date shared by every fact.
Net revenue
Gross order revenue minus refunds, each aggregated separately before combining.
Reconciliation
Checking warehouse totals against a trusted source such as payment provider reports.

Visual diagram

Loading interactive diagram

Theory & example queries

Schema and warehouse design

In the application database, every table gets a primary key, foreign keys and checks: order_items (order_id REFERENCES orders, product_id REFERENCES products, quantity int CHECK (quantity > 0), unit_price numeric(12,2) NOT NULL), with the price captured at purchase time. Index the API's access paths, such as orders (customer_id, created_at DESC). Subscriptions record plan, seats and status changes as events, so history isn't overwritten.

In the warehouse, staging models clean each source table, intermediate models match payments and refunds to orders and expand subscriptions into one row per month, and marts expose facts at a declared grain. fct_order_items holds quantity, gross amount and keys to dim_customer (type 2 for segment and country), dim_product and dim_date; fct_subscription_months holds MRR per subscription per month. Partition or cluster the large facts by date so most queries read only recent data, and build them incrementally.

Net revenue by month without fan-outQuery 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  sales AS (3    SELECT4      d.year_month,5      SUM(f.gross_amount) AS gross6    FROM7      fct_order_items f8      JOIN dim_date d ON d.date_key = f.order_date_key9    GROUP BY10      111  ),12  refunds AS (13    SELECT14      d.year_month,15      SUM(r.amount) AS refunded16    FROM17      fct_refunds r18      JOIN dim_date d ON d.date_key = r.refund_date_key19    GROUP BY20      121  )22SELECT23  s.year_month,24  s.gross,25  COALESCE(r.refunded, 0) AS refunded,26  s.gross - COALESCE(r.refunded, 0) AS net27FROM28  sales s29  LEFT JOIN refunds r USING (year_month)30ORDER BY31  1;
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.
Expected output3 sample rows
Expected output
year_monthgrossrefundednet
2026-081845006200178300
2026-092037508100195650
2026-102264004750221650

Note: Illustrative warehouse facts and currency amounts for three months.

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

Key takeaway: Constraints in the app; declared grains, conformed dimensions and date partitioning in the warehouse.

Metrics, performance and trust

Each metric reuses a pattern from earlier lessons: AOV is net revenue ÷ distinct orders; new vs returning revenue uses ROW_NUMBER over each customer's orders; top 3 products per category is ROW_NUMBER partitioned by category with rn <= 3; MRR movements compare each subscription's MRR with LAG over months (new, expansion, contraction, churn); retention is a cohort triangle by first-order month. Write each as a CTE pipeline with a grain comment per step.

Make it fast: incremental fact builds, date partitions, a small daily summary table or materialised view for the dashboard, and EXPLAIN on anything slow. Make it trustworthy: unique and not_null tests on every key, relationships tests from facts to dimensions, accepted values for statuses, freshness checks on sources, and a daily reconciliation of net revenue against the payment provider's settlement report. Mask customer PII in the marts analysts use.

Top 3 products per category last 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  ranked AS (3    SELECT4      p.category,5      p.name,6      SUM(f.gross_amount) AS revenue,7      ROW_NUMBER() OVER (8        PARTITION BY9          p.category10        ORDER BY11          SUM(f.gross_amount) DESC,12          p.name13      ) AS rn14    FROM15      fct_order_items f16      JOIN dim_product p ON p.product_key = f.product_key17      JOIN dim_date d ON d.date_key = f.order_date_key18    WHERE19      d.year_month = '2026-10'20    GROUP BY21      p.category,22      p.name23  )24SELECT25  category,26  name,27  revenue28FROM29  ranked30WHERE31  rn <= 332ORDER BY33  category,34  rn;
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/34
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
categorynamerevenue
BooksSQL Field Guide18400
BooksData Modeling12650
ElectronicsUSB-C Hub35200
ElectronicsWireless Mouse24100

Note: Shows an illustrative excerpt; a full result contains up to three products per category.

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

Key takeaway: Reuse proven patterns per metric; tests and reconciliation before anyone sees a number.

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 1Plan

Requirements and grains

List each dashboard metric with its exact definition, and the grain of each fact table that supports it.

Focus at this step

net revenue = gross − refunds · fct_order_items: one row per line

What to watch at this step
Metrics
6 defined
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

This capstone builds analytics end to end for a business that sells products online and a monthly "Pro" membership. You design the application schema (customers, products, orders, order_items, payments, refunds, subscriptions), model a warehouse (staging → intermediate → marts with fct_order_items, fct_subscription_months, dim_customer, dim_product, dim_date), write the metrics (net revenue, AOV, repeat rate, top products per category, MRR movements, cohort retention), and make it fast and trustworthy with partitions, indexes, incremental models and tests.

Why it matters: Interviews for analyst, analytics-engineer and data-engineer roles increasingly use a take-home or a whiteboard case like this, because it shows whether you can connect the pieces: grain, joins, window functions, CTE pipelines, indexing and data quality. Working through one complete project is also the best way to see how the earlier lessons fit together.

When to reach for it

  • Take-home assignments for analytics roles
  • A portfolio project that shows end-to-end skills
  • Planning a real company's first warehouse

When to avoid or be careful

  • Joining orders, items and refunds before aggregating
  • Metrics without written definitions
  • Dashboards built before tests and reconciliation pass

Design choices in the capstone

Star schema marts (facts + conformed dimensions)
Best for: Many metrics and BI tools across teams

Strengths: Clear grains; correct joins; reusable dimensions.

Watch out: More models to build and test.

One wide table per dashboard
Best for: A single, stable report

Strengths: Simple for one consumer.

Watch out: Duplicated logic; mixed grains; hard to extend.

Querying the OLTP database directly
Best for: Early prototypes

Strengths: No pipeline to build.

Watch out: Slows the app; no history; logic scattered across reports.

Interview signals & numbers to know

When this topic comes up

  • “Design an analytics warehouse for an e-commerce company”
  • “Calculate MRR and churn from subscription data”
  • “Take-home: build these six metrics”
  • End-to-end data modelling
  • Metric definitions

Benchmarks & rules of thumb

2 -
fact grains: order line, subscription-month
3 -
conformed dimensions: customer, product, date
₹0 -
allowed difference from the payments reconciliation

Common mistakes & follow-ups

Common interview mistakes

  • Joining refunds to order lines and summing both, counting each refund once per line in the order.
  • Computing MRR from the current subscriptions table, losing every past plan change and churn.
  • Shipping the dashboard first and discovering a week later that revenue is 6% above the payment provider's total.

Likely interviewer follow-ups

  • What tables and grains would you design for this business?
  • How would you calculate net revenue and MRR movements correctly?
  • How would you prove the dashboard's numbers are right?
Interview tip: In a take-home, include a short README with metric definitions, grains, assumptions and the reconciliation result. Reviewers value that clarity as much as the SQL itself.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Capstone Project: Designing, Optimizing & Querying a Full E-Commerce & SaaS Analytics Warehouse with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Cloud SQL Databases & Analytical Engines (Snowflake, BigQuery, DuckDB)