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 80/ 160
04. Subqueries & Common Table Expressions (CTEs)

Structuring Production Analytical SQL Models

Organize staging → intermediate → mart models for maintainable warehouse SQL.

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

In plain words

Clean the raw data first, then combine it, then shape it for the people who use it.

Think of it like…

A restaurant kitchen: deliveries are washed and prepped at one station (staging), sauces and components are made at another (intermediate), and plates are assembled for the customer at the pass (marts). Nobody plates food straight from the delivery van.

Where you’ve seen it

A D2C company had 40 dashboards, each computing revenue from raw Shopify and Stripe tables with different refund handling. The team built stg_shopify__orders and stg_stripe__refunds, an int_order_payments model that matches them, and one fct_orders mart. Dashboards were repointed to fct_orders, and the finance and marketing revenue numbers matched for the first time.

Words you’ll hear

Staging model
One per source table: renames, casts and light cleaning, no joins.
Intermediate model
Reusable joins and business logic between staging and marts.
Mart
Business-facing facts and dimensions, organised by domain.
ref()
dbt's way for one model to depend on another, building the dependency graph.

Visual diagram

Loading interactive diagram

Theory & example queries

What belongs in each layer

Staging models map one-to-one to source tables: select only needed columns, rename them to house conventions (id → order_id), cast types, convert currencies or time zones, and remove exact duplicates. No joins and no business logic, so a change in the source system is fixed in exactly one place. A common naming pattern is stg_<source>__<table>.

Intermediate models hold logic that's too complex or too reused to live in a mart: matching payments to orders, sessionising events, pivoting line items. Marts are shaped for consumers and grouped by business area (finance, marketing, product): fct_ models at a declared grain and dim_ models with descriptive attributes. Dashboards, notebooks and reverse-ETL jobs read marts only.

A staging modelQuery 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.sqlReadable preview
1select id2as order_id,3  customer_id,4  cast(total_price5as numeric(12,2))6as amount,7  lower(financial_status)8as payment_status,9  created_at at time zone 'UTC'10as created_at11from {{ source('shopify',12  'orders') }}13where test = false
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/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative staged orders2 sample rows
Representative staged orders
order_idcustomer_idamountpayment_statuscreated_at
710142249.99paid2026-11-20 09:15:00
71021875.5pending2026-11-20 11:42:00

Note: The values illustrate two non-test Shopify orders after dbt compiles source('shopify', 'orders'). Timestamp text and cast behavior depend on the warehouse dialect and source types.

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

Key takeaway: Staging cleans one source, intermediate combines, marts serve consumers.

Tests, materialisation and growth

Every model declares its primary key with unique and not_null tests; foreign keys get relationships tests, and status columns get accepted_values. Source freshness checks warn when a loader stops. These run on every build in CI, so a source change that introduces duplicates fails the pipeline instead of silently inflating revenue.

Choose materialisation per layer: staging as views (cheap, always fresh), intermediate as views or ephemeral, marts as tables, or as incremental models that only process new or changed rows for large facts: {{ config(materialized='incremental', unique_key='order_id') }} with a filter on updated_at. As the project grows, keep the layers strict: a mart reading a raw table, or a staging model with joins, is the first step back to spaghetti.

Tests in YAML

models: - name: fct_orders columns: - name: order_id tests: [unique, not_null] - name: customer_id tests: - relationships: {to: ref('dim_customers'), field: customer_id}

Key takeaway: Test every key, views for staging, tables or incremental for marts.
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 1Staging

Stage each source

Create one model per source table that renames, casts and lightly cleans, with no joins.

Focus at this step

stg_shopify__orders

What to watch at this step
Mapping
1 source : 1 model
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Production warehouse SQL is organised in layers of models, each a SELECT saved as a view or table. Staging models clean one source table each (rename, cast, fix time zones). Intermediate models join and apply business logic. Marts are the facts and dimensions people query, such as fct_orders and dim_customers. Models reference each other rather than raw tables, so every metric is defined once and the dependency graph is explicit. dbt is the most common tool for this.

Why it matters: Without structure, every dashboard re-implements "revenue" slightly differently, and a renamed source column breaks forty queries. Layered models give one place to fix each kind of problem: source quirks in staging, business rules in intermediate, consumer-facing shape in marts. Analytics-engineering interviews almost always ask how you'd structure a warehouse project.

When to reach for it

  • Any warehouse with more than a couple of sources
  • Teams where finance and marketing must agree on numbers
  • Projects run with dbt or similar tools

When to avoid or be careful

  • Dashboards querying raw source tables
  • Joins and business rules in staging models
  • Marts without primary-key tests

Ways to organise warehouse SQL

Layered models (staging → intermediate → marts)
Best for: Teams with several sources and many consumers

Strengths: One definition per metric; explicit dependencies; tested.

Watch out: More models and conventions to learn.

SQL inside each dashboard
Best for: A single analyst with a handful of reports

Strengths: Fast to start.

Watch out: Duplicated, drifting logic; breaks when sources change.

One big wide table
Best for: A narrow, stable use case

Strengths: Simple for consumers.

Watch out: Hard to change; mixes grains; slow to rebuild.

Interview signals & numbers to know

When this topic comes up

  • “How would you structure our dbt project?”
  • “Finance and marketing report different revenue”
  • “A source column was renamed and dashboards broke”
  • Staging, intermediate and marts
  • Data tests

Benchmarks & rules of thumb

3 -
layers: staging, intermediate, marts
1:1 -
staging models to source tables
2 -
tests every key needs: unique, not_null

Common mistakes & follow-ups

Common interview mistakes

  • Joining two sources in a staging model, so a change in either breaks a model that should only clean one table.
  • Letting a dashboard read an intermediate model, then changing it and breaking the dashboard.
  • Building a large fact as a full table rebuild every hour when an incremental model would process only new rows.

Likely interviewer follow-ups

  • What goes in a staging model, and what doesn't?
  • How do you make sure revenue is defined only once?
  • When would you make a model incremental?
Interview tip: Describe the three layers with one example model each, then mention key tests and materialisation. That's the structure analytics-engineering interviewers want to hear.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Structuring Production Analytical SQL Models with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Sessionization Queries (Grouping User Events by Inactivity Timeout)
Next topic
Window Functions vs GROUP BY Aggregations (Preserving Row Granularity)