This page requires JavaScript to display.
W
Unpacking...
← Advanced Data Engineering
Advanced Data Engineering

Data Warehousing Deep Dive

How analytical data is stored, modelled and optimised: architectures, facts and dimensions, SCDs, indexing and clustering, sharding and data management strategies.

Contents
1. OLTP vs OLAP 2. Data Warehousing Architecture 3. Facts vs Dimensions 4. Star and Snowflake Schemas 5. ETL, ELT and the Tools 6. Slowly Changing Dimensions: Types 1, 2 and 3 7. Introduction to dbt and Airflow 8. Indexing and Clustering 9. Sharding and Query Optimisation 10. Data Management Strategies

1. OLTP vs OLAP

Operational systems run the business; analytical systems help understand it. They have opposite workloads, so they are built differently, and the warehouse exists so analytics never slows down the systems customers use.

OLTP (operational)OLAP (analytical)
PurposeRun transactions: place an order, move moneyAnalyse: revenue by region and month
QueriesMany short reads and writes of a few rows by keyFew long scans and aggregations over millions of rows
DataCurrent stateHistory, often years
ModelNormalised (3NF)Denormalised: star schemas, wide tables
StorageRow store, B-tree indexesColumn store, compression, partitioning
UsersApplications, thousands of concurrent sessionsAnalysts, BI tools, data scientists
ExamplesPostgreSQL, MySQL, Oracle, DynamoDBSnowflake, BigQuery, Redshift, Databricks SQL, Synapse
 OLTP sources            ingestion            WAREHOUSE / LAKEHOUSE                consumers
 orders DB, CRM,   --->  CDC, batch,   --->   staging -> integrated -> marts  --->  BI, ML,
 payments, files         streaming            (history, conformed, modelled)        reverse ETL

Deep dive: the Data Warehouse guide covers this in more depth.

2. Data Warehousing Architecture

Layers

LayerContentsAlso called
Staging / rawSource data as delivered, plus load metadataLanding, bronze
IntegrationCleaned, conformed, historised entitiesCore, EDW, silver
PresentationStar schemas and marts per business processMarts, gold
SemanticBusiness metrics and definitionsSemantic layer, metrics layer

Design approaches

ApproachIdeaStrengthWeakness
Inmon (top-down)A normalised enterprise warehouse first, then marts from itSingle integrated truthSlow to deliver value
Kimball (bottom-up)Dimensional marts per business process, joined by conformed dimensions (bus architecture)Fast delivery, business-friendlyNeeds discipline to keep dimensions conformed
Data Vault 2.0Hubs (keys), links (relationships), satellites (history) for integration; marts on topAbsorbs many changing sources, full auditMore tables, needs marts for users
Lakehouse / medallionBronze, silver, gold on open table formats over object storageOne copy for BI and ML, cheap storageNeeds governance and table maintenance

Cloud warehouse architectures

StyleHow it worksExamples
Separated storage and computeData in cloud storage; independent compute clusters scale and pause separatelySnowflake, Databricks SQL
ServerlessYou submit queries; the service allocates compute; pay per data scanned or slotBigQuery, Athena, Redshift Serverless
MPP clusterData distributed across nodes, each processing its slice in parallelRedshift provisioned, Synapse dedicated pools
Say this in the interview

"A warehouse has staging, integration and presentation layers, plus a semantic layer. Inmon builds an integrated 3NF warehouse first; Kimball builds dimensional marts joined by conformed dimensions; Data Vault integrates many sources with hubs, links and satellites. Modern platforms separate storage from compute, or run serverless, and the lakehouse brings the same layering to open formats."

3. Facts vs Dimensions

A fact records a business event or measurement (numbers you aggregate). A dimension describes the context of the event (who, what, where, when) and is used to filter and group. Every fact table has a declared grain: exactly what one row represents.

Fact tableDimension table
ContainsMeasures + foreign keys to dimensionsDescriptive attributes + surrogate key
SizeVery tall (millions to billions of rows), narrowShort, wide
ChangesMostly appendedAttributes change slowly (SCD)
Examplefact_sales: date_key, product_key, store_key, qty, amountdim_product: product_key, name, brand, category

Types of measures

MeasureCan be summed acrossExample
AdditiveAll dimensionsSales amount, quantity
Semi-additiveSome dimensions, not timeAccount balance, stock on hand
Non-additiveNone; recompute from componentsRatios, percentages, unit price

Semi-additive measures are a classic trap. Summing daily balances over time is meaningless; use the balance at the end of the period:

SELECT account_id,
       SUM(balance)                                  AS wrong_sum_over_days,
       ARG_MAX(balance, snapshot_date)               AS closing_balance,
       ROUND(AVG(balance), 2)                        AS average_daily_balance
FROM fact_account_balance
GROUP BY account_id
ORDER BY account_id;
account_idwrong_sum_over_daysclosing_balanceaverage_daily_balance
A13,100.00900.001,033.33
A21,650.00700.00550.0

Types of fact tables

TypeGrainExample
TransactionOne row per eventOne row per order line
Periodic snapshotOne row per entity per periodDaily account balance, monthly inventory
Accumulating snapshotOne row per process instance, updated as milestones happenOrder with ordered, packed, shipped and delivered dates
FactlessRecords that something happened, no measuresStudent attended class; product on promotion

Types of dimensions

TypeMeaningExample
ConformedShared, identical meaning across factsdim_date, dim_customer used by sales and returns
Role-playingOne dimension used in several rolesdim_date as order date, ship date, delivery date
DegenerateA dimension key with no table, stored in the factorder_number on the sales fact
JunkLow-cardinality flags combined into one tableis_gift, payment_type, channel
Mini-dimensionFast-changing attributes split offCustomer age band, income band
OutriggerA dimension referenced by another dimensiondim_customer → dim_geography
Say this in the interview

"Facts hold measures at a declared grain; dimensions hold the descriptive context. I distinguish additive, semi-additive and non-additive measures (never sum balances over time), choose the fact type (transaction, periodic snapshot, accumulating snapshot or factless) and use conformed, role-playing, degenerate and junk dimensions where they fit."

4. Star and Snowflake Schemas

 STAR                                         SNOWFLAKE
            dim_date                                     dim_date
               |                                            |
 dim_store -- fact_sales -- dim_product        dim_store -- fact_sales -- dim_product -- dim_category -- dim_department
               |            (name, category,                |
            dim_customer     department)                 dim_customer -- dim_geography
StarSnowflake
DimensionsDenormalised: one table per dimensionNormalised into sub-tables
Joins per queryOne per dimensionMore (chains of joins)
Query speed and simplicityFaster, simpler for BISlower, more complex
Storage and redundancySome repetition in dimensionsLess repetition
UseDefault for analytics and BI toolsVery large or shared hierarchies; some MDM-driven designs

Both give the same answer; the star needs fewer joins:

-- star: one join
SELECT d.department, SUM(f.amount) AS revenue
FROM fact_sales f JOIN dim_product_star d USING (product_key)
GROUP BY d.department ORDER BY revenue DESC;
departmentrevenue
Electronics400.00
Home150.00
-- snowflake: two joins for the same answer
SELECT c.department, SUM(f.amount) AS revenue
FROM fact_sales f
JOIN dim_product_snow p USING (product_key)
JOIN dim_category c     USING (category_key)
GROUP BY c.department ORDER BY revenue DESC;
departmentrevenue
Electronics400.00
Home150.00
Say this in the interview

"A star schema has a central fact table with denormalised dimensions, so queries need one join per dimension and BI tools work well. A snowflake normalises dimensions into sub-tables, saving some storage at the cost of more joins. Columnar warehouses compress repeated dimension values well, so I default to stars."

5. ETL, ELT and the Tools

ETLELT
OrderExtract → Transform (on an ETL server) → LoadExtract → Load raw → Transform inside the warehouse
Where compute runsETL engine (Informatica, SSIS, Talend)The warehouse or lakehouse itself (SQL, Spark)
Raw data kept?Often notYes: replay and audit are easy
FitsOn-premises, limited warehouse compute, strict pre-load maskingCloud warehouses with elastic compute: the modern default
StageTools
Extract and load (EL)Fivetran, Airbyte, Stitch, Azure Data Factory, AWS DMS, Debezium, Lakeflow Connect
Transform (T)dbt, Spark, Databricks Lakeflow Declarative Pipelines, Snowflake Dynamic Tables, SQL
Classic ETL suitesInformatica, Talend, SSIS, IBM DataStage, Matillion
OrchestrationAirflow, Dagster, Prefect, Lakeflow Jobs, ADF, Step Functions
Reverse ETLHightouch, Census: push warehouse data back into CRMs and SaaS tools
Say this in the interview

"ETL transforms before loading; ELT loads raw data first and transforms inside the warehouse with its elastic compute, which keeps raw history for replay and suits the cloud. A typical modern stack is Fivetran or Airbyte for EL, dbt or Spark for T, and Airflow for orchestration."

6. Slowly Changing Dimensions: Types 1, 2 and 3

Dimension attributes change: a customer moves city, a product changes category. The SCD type decides what happens to history. In the examples, the staging table says Asha moved from Pune to Mumbai, Ravi is unchanged, and Meera is new.

TypeBehaviourHistoryUse for
0Never changeOriginal value keptDate of birth, original signup channel
1OverwriteNoneCorrections, attributes nobody analyses historically
2New row per change, with validity datesFullRegion, segment, anything reports group history by
3Previous value in an extra columnOne previous valueBefore/after comparisons, e.g. a sales territory realignment
4Current table + separate history tableFull, kept apartVery fast-changing attributes
6Type 2 rows + Type 1 "current" column on every rowFull + current viewReport by either historical or current value

Type 1: overwrite

MERGE INTO dim_customer_scd1 t
USING stg_customer s ON t.customer_id = s.customer_id
WHEN MATCHED AND t.city <> s.city THEN UPDATE SET city = s.city
WHEN NOT MATCHED THEN INSERT VALUES (s.customer_id, s.name, s.city);
SELECT * FROM dim_customer_scd1 ORDER BY customer_id;
customer_idnamecity
1AshaMumbai
2RaviDelhi
3MeeraChennai

Type 2: close the old row, insert a new version

-- 1. close current rows whose tracked attributes changed
UPDATE dim_customer_scd2 t
SET valid_to = s.changed_on - 1, is_current = false
FROM stg_customer s
WHERE t.customer_id = s.customer_id AND t.is_current AND t.city <> s.city;

-- 2. insert a new current version for changed and brand-new customers
INSERT INTO dim_customer_scd2
SELECT (SELECT MAX(customer_sk) FROM dim_customer_scd2) + ROW_NUMBER() OVER (ORDER BY s.customer_id),
       s.customer_id, s.name, s.city, s.changed_on, NULL, true
FROM stg_customer s
LEFT JOIN dim_customer_scd2 t ON t.customer_id = s.customer_id AND t.is_current
WHERE t.customer_id IS NULL;

SELECT * FROM dim_customer_scd2 ORDER BY customer_id, valid_from;
customer_skcustomer_idnamecityvalid_fromvalid_tois_current
11AshaPune2025-01-012026-02-28False
31AshaMumbai2026-03-01NULLTrue
22RaviDelhi2025-01-01NULLTrue
43MeeraChennai2026-03-01NULLTrue

Step 1 runs first, so a changed customer has no current row left and step 2 inserts its new version. Ravi is unchanged and keeps his single row. Facts store customer_sk, so sales before 1 March stay with Pune and later sales go to Mumbai. Running the load twice changes nothing.

Type 3: keep the previous value in a column

UPDATE dim_customer_scd3 t
SET previous_city = t.city, city = s.city, city_changed_on = s.changed_on
FROM stg_customer s
WHERE t.customer_id = s.customer_id AND t.city <> s.city;
SELECT * FROM dim_customer_scd3 ORDER BY customer_id;
customer_idnamecityprevious_citycity_changed_on
1AshaMumbaiPune2026-03-01
2RaviDelhiNULLNULL
Say this in the interview

"SCD Type 1 overwrites, so no history; Type 2 adds a new row with validity dates and a current flag, giving full history, and facts point to the surrogate key valid at the event time; Type 3 keeps one previous value in its own column. I choose the type per attribute, and make SCD2 loads idempotent by only acting on rows whose tracked attributes actually changed."

7. Introduction to dbt and Airflow

dbt transforms data inside the warehouse with SQL SELECT statements; it handles dependencies, tests, documentation and incremental builds. Airflow schedules and orchestrates the whole pipeline: extract, load, run dbt, run quality checks, notify.

A dbt model and its tests

-- models/marts/fct_daily_sales.sql
{{ config(materialized='incremental', unique_key=['sale_date', 'store_id']) }}

SELECT order_date AS sale_date, store_id, SUM(amount) AS revenue, COUNT(*) AS orders
FROM {{ ref('stg_orders') }}
WHERE status = 'DELIVERED'
{% if is_incremental() %}
  AND order_date >= (SELECT MAX(sale_date) - 3 FROM {{ this }})   -- reprocess 3 days for late data
{% endif %}
GROUP BY order_date, store_id
# models/marts/fct_daily_sales.yml
models:
  - name: fct_daily_sales
    columns:
      - name: store_id
        data_tests: [not_null, {relationships: {to: ref('dim_store'), field: store_id}}]
      - name: revenue
        data_tests: [not_null]

An Airflow DAG that runs it

from datetime import datetime
from airflow.decorators import dag, task
from airflow.operators.bash import BashOperator

@dag(schedule="0 2 * * *", start_date=datetime(2026, 1, 1), catchup=False, tags=["sales"])
def daily_sales():
    @task
    def extract_orders(ds=None):
        print(f"extracting orders for {ds}")  # e.g. copy files to the landing zone

    run_dbt = BashOperator(task_id="dbt_build",
                           bash_command="dbt build --select +fct_daily_sales --target prod")
    extract_orders() >> run_dbt

daily_sales()

dbt and Airflow project files: follows the official syntax but was not executed here, because it needs a live cloud account or service.

Deep dives: dbt and Apache Airflow.

Say this in the interview

"dbt turns SELECT statements into tested, documented, dependency-ordered tables inside the warehouse, including incremental models. Airflow orchestrates the end-to-end pipeline on a schedule with retries and alerts, and typically calls dbt build after loading data."

8. Indexing and Clustering

StructureHow it helpsWhere
B-tree indexLogarithmic lookup and range scans by keyOLTP databases
Composite indexIndex on (a, b); usable for filters on a, or a and b (leftmost prefix rule)OLTP databases
Covering indexContains every column the query needs: no table lookupOLTP, read-heavy queries
Clustered indexTable rows physically ordered by the keySQL Server, MySQL InnoDB primary key
Bitmap indexBit arrays for low-cardinality columns; fast AND/OROracle warehouses
Zone maps / min-max statisticsSkip blocks whose min/max cannot match the filterParquet, Snowflake micro-partitions, Redshift blocks
Clustering keys / sort keysCo-locate similar values so zone maps prune moreSnowflake clustering keys, Redshift sort keys, BigQuery clustering
Z-order / liquid clusteringMulti-column clustering for filesDelta Lake, Databricks

The leftmost-prefix rule

import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE sales (store_id INT, sale_date TEXT, amount REAL)")
con.execute("CREATE INDEX ix_store_date ON sales(store_id, sale_date)")
for q in ["SELECT * FROM sales WHERE store_id = 5 AND sale_date >= '2026-03-01'",
          "SELECT * FROM sales WHERE store_id = 5",
          "SELECT * FROM sales WHERE sale_date >= '2026-03-01'"]:
    plan = con.execute("EXPLAIN QUERY PLAN " + q).fetchall()[0][3]
    print(f"{q.split('WHERE')[1].strip():45} -> {plan}")
Output
store_id = 5 AND sale_date >= '2026-03-01'    -> SEARCH sales USING INDEX ix_store_date (store_id=? AND sale_date>?)
store_id = 5                                  -> SEARCH sales USING INDEX ix_store_date (store_id=?)
sale_date >= '2026-03-01'                     -> SCAN sales

An index on (store_id, sale_date) is used when the filter includes store_id, but a filter on sale_date alone falls back to a full scan. Order composite index columns by how queries filter: equality columns first, then range columns.

Warehouses do not use classic indexes

Columnar warehouses scan instead of seeking, so they speed up queries by skipping data: partitions by date, and min/max statistics per block or file. Clustering data on common filter columns makes those statistics selective. Indexes have a cost too: every index slows writes and uses storage, so add them for real query patterns, not speculatively.

Say this in the interview

"In OLTP databases I use B-tree indexes, composite indexes ordered by the leftmost-prefix rule, and covering indexes for hot queries, knowing each index slows writes. Analytical engines skip data instead: partitions plus min/max statistics, made effective by clustering or sort keys, Z-order or liquid clustering on common filter columns."

9. Sharding and Query Optimisation

Partitioning splits a table into parts within one system (often by date). Sharding spreads data across separate machines so storage and write throughput scale horizontally. Each shard holds a subset of rows chosen by a shard key.

StrategyHowStrengthRisk
RangeKey ranges per shard (A–F, G–M ...)Efficient range queriesHot spots (all new rows on the last shard)
Hashhash(key) mod NEven distributionRange queries hit every shard; adding a shard moves most keys
Consistent hashingKeys and shards placed on a hash ringAdding a shard moves only about 1/N of keysMore complex
Directory / geoA lookup table maps key to shardFlexible; data residency by regionThe directory is a dependency

Why consistent hashing matters when you add a shard

import hashlib, bisect

def h(s):
    return int(hashlib.md5(s.encode()).hexdigest(), 16)

keys = [f"customer_{i}" for i in range(10_000)]

def mod_n(key, n):
    return h(key) % n

def ring(nodes, vnodes=100):
    points = sorted((h(f"{n}#{v}"), n) for n in nodes for v in range(vnodes))
    hashes = [p for p, _ in points]
    def lookup(key):
        i = bisect.bisect(hashes, h(key)) % len(points)
        return points[i][1]
    return lookup

moved_mod = sum(mod_n(k, 4) != mod_n(k, 5) for k in keys)
r4, r5 = ring(["s1", "s2", "s3", "s4"]), ring(["s1", "s2", "s3", "s4", "s5"])
moved_ring = sum(r4(k) != r5(k) for k in keys)
print(f"adding a 5th shard: hash mod N moves {moved_mod / len(keys):.0%} of keys, "
      f"consistent hashing moves {moved_ring / len(keys):.0%}")
Output
adding a 5th shard: hash mod N moves 80% of keys, consistent hashing moves 17%

Cassandra, DynamoDB and many caches use consistent hashing with virtual nodes for exactly this reason: scaling out should not reshuffle almost all data.

Query optimisation checklist

LeverWhat to do
Read the planEXPLAIN / query profile: scans, joins, row estimates, spills
Prune dataFilter on partition and cluster columns; keep predicates sargable
Push downSelect only needed columns; filter before joins (projection and predicate pushdown)
Join strategyBroadcast small tables; avoid many-to-many joins; pre-aggregate
StatisticsKeep table statistics fresh so the optimiser estimates well
SkewDetect hot keys; salt or isolate them
ReuseMaterialized views, aggregate tables, result caching
Right-size computeSeparate warehouses or clusters per workload; scale for concurrency
Say this in the interview

"Partitioning splits a table inside one system; sharding spreads it across machines by a shard key. Range sharding suits range queries but creates hot spots, hash sharding spreads evenly, and consistent hashing lets me add shards while moving only about 1/N of keys. For query optimisation I read the plan, prune with partitions and clustering, push filters and projections down, choose join strategies, keep statistics fresh and handle skew."

10. Data Management Strategies

StrategyWhat it meansTypical implementation
Lifecycle and tieringHot data on fast storage, cold data on cheap storageS3 Standard → Infrequent Access → Glacier; BigQuery long-term storage pricing
Retention and archivalKeep data as long as needed and no longerRetention policies per dataset; legal holds; purge jobs
PartitioningSplit large tables by date or keyPartitioned tables; partition expiry
Compaction and maintenanceMerge small files; remove obsolete versionsOPTIMIZE / VACUUM (Delta), rewrite_data_files / expire_snapshots (Iceberg)
Backup and recoveryRecover from mistakes and disastersTime travel, snapshots, cross-region replication, tested restores
Data qualityDetect bad data before users doTests, expectations, quarantine, reconciliation
Metadata and governanceKnow what data exists, who owns it, who may use itCatalog, glossary, lineage, classification, access policies
Master and reference dataOne version of core entities and codesMDM hub, reference tables
Cost managementPay for what is usedAuto-suspend compute, quotas, tagging, query cost monitoring

Deep dives: the Enterprise Data Architect guide covers governance, MDM, lineage and data quality KPIs at enterprise level; Delta Lake and Apache Iceberg cover table maintenance.

Say this in the interview

"Data management strategies keep a platform reliable and affordable: lifecycle tiering and retention policies, partitioning, compaction and snapshot expiry, tested backups, quality checks, metadata and governance, master data, and cost controls such as auto-suspending compute."