Structuring Production Analytical SQL Models
Organize staging → intermediate → mart models for maintainable warehouse SQL.
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
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.
select idas order_id, customer_id, cast(total_priceas numeric(12,2))as amount, lower(financial_status)as payment_status, created_at at time zone 'UTC'as created_atfrom {{ source('shopify', 'orders') }}where test = falsePostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative staged orders2 sample rows
| order_id | customer_id | amount | payment_status | created_at |
|---|---|---|---|---|
| 7101 | 42 | 249.99 | paid | 2026-11-20 09:15:00 |
| 7102 | 18 | 75.5 | pending | 2026-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.
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.
models: - name: fct_orders columns: - name: order_id tests: [unique, not_null] - name: customer_id tests: - relationships: {to: ref('dim_customers'), field: customer_id}
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Stage each source
Create one model per source table that renames, casts and lightly cleans, with no joins.
stg_shopify__orders
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
Strengths: One definition per metric; explicit dependencies; tested.
Watch out: More models and conventions to learn.
Strengths: Fast to start.
Watch out: Duplicated, drifting logic; breaks when sources change.
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?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Structuring Production Analytical SQL Models with hands-on SQL practice and interview Q&A.