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.
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) | |
|---|---|---|
| Purpose | Run transactions: place an order, move money | Analyse: revenue by region and month |
| Queries | Many short reads and writes of a few rows by key | Few long scans and aggregations over millions of rows |
| Data | Current state | History, often years |
| Model | Normalised (3NF) | Denormalised: star schemas, wide tables |
| Storage | Row store, B-tree indexes | Column store, compression, partitioning |
| Users | Applications, thousands of concurrent sessions | Analysts, BI tools, data scientists |
| Examples | PostgreSQL, MySQL, Oracle, DynamoDB | Snowflake, 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
| Layer | Contents | Also called |
|---|---|---|
| Staging / raw | Source data as delivered, plus load metadata | Landing, bronze |
| Integration | Cleaned, conformed, historised entities | Core, EDW, silver |
| Presentation | Star schemas and marts per business process | Marts, gold |
| Semantic | Business metrics and definitions | Semantic layer, metrics layer |
Design approaches
| Approach | Idea | Strength | Weakness |
|---|---|---|---|
| Inmon (top-down) | A normalised enterprise warehouse first, then marts from it | Single integrated truth | Slow to deliver value |
| Kimball (bottom-up) | Dimensional marts per business process, joined by conformed dimensions (bus architecture) | Fast delivery, business-friendly | Needs discipline to keep dimensions conformed |
| Data Vault 2.0 | Hubs (keys), links (relationships), satellites (history) for integration; marts on top | Absorbs many changing sources, full audit | More tables, needs marts for users |
| Lakehouse / medallion | Bronze, silver, gold on open table formats over object storage | One copy for BI and ML, cheap storage | Needs governance and table maintenance |
Cloud warehouse architectures
| Style | How it works | Examples |
|---|---|---|
| Separated storage and compute | Data in cloud storage; independent compute clusters scale and pause separately | Snowflake, Databricks SQL |
| Serverless | You submit queries; the service allocates compute; pay per data scanned or slot | BigQuery, Athena, Redshift Serverless |
| MPP cluster | Data distributed across nodes, each processing its slice in parallel | Redshift provisioned, Synapse dedicated pools |
"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 table | Dimension table | |
|---|---|---|
| Contains | Measures + foreign keys to dimensions | Descriptive attributes + surrogate key |
| Size | Very tall (millions to billions of rows), narrow | Short, wide |
| Changes | Mostly appended | Attributes change slowly (SCD) |
| Example | fact_sales: date_key, product_key, store_key, qty, amount | dim_product: product_key, name, brand, category |
Types of measures
| Measure | Can be summed across | Example |
|---|---|---|
| Additive | All dimensions | Sales amount, quantity |
| Semi-additive | Some dimensions, not time | Account balance, stock on hand |
| Non-additive | None; recompute from components | Ratios, 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_id | wrong_sum_over_days | closing_balance | average_daily_balance |
|---|---|---|---|
| A1 | 3,100.00 | 900.00 | 1,033.33 |
| A2 | 1,650.00 | 700.00 | 550.0 |
Types of fact tables
| Type | Grain | Example |
|---|---|---|
| Transaction | One row per event | One row per order line |
| Periodic snapshot | One row per entity per period | Daily account balance, monthly inventory |
| Accumulating snapshot | One row per process instance, updated as milestones happen | Order with ordered, packed, shipped and delivered dates |
| Factless | Records that something happened, no measures | Student attended class; product on promotion |
Types of dimensions
| Type | Meaning | Example |
|---|---|---|
| Conformed | Shared, identical meaning across facts | dim_date, dim_customer used by sales and returns |
| Role-playing | One dimension used in several roles | dim_date as order date, ship date, delivery date |
| Degenerate | A dimension key with no table, stored in the fact | order_number on the sales fact |
| Junk | Low-cardinality flags combined into one table | is_gift, payment_type, channel |
| Mini-dimension | Fast-changing attributes split off | Customer age band, income band |
| Outrigger | A dimension referenced by another dimension | dim_customer → dim_geography |
"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
| Star | Snowflake | |
|---|---|---|
| Dimensions | Denormalised: one table per dimension | Normalised into sub-tables |
| Joins per query | One per dimension | More (chains of joins) |
| Query speed and simplicity | Faster, simpler for BI | Slower, more complex |
| Storage and redundancy | Some repetition in dimensions | Less repetition |
| Use | Default for analytics and BI tools | Very 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;
| department | revenue |
|---|---|
| Electronics | 400.00 |
| Home | 150.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;
| department | revenue |
|---|---|
| Electronics | 400.00 |
| Home | 150.00 |
"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
| ETL | ELT | |
|---|---|---|
| Order | Extract → Transform (on an ETL server) → Load | Extract → Load raw → Transform inside the warehouse |
| Where compute runs | ETL engine (Informatica, SSIS, Talend) | The warehouse or lakehouse itself (SQL, Spark) |
| Raw data kept? | Often not | Yes: replay and audit are easy |
| Fits | On-premises, limited warehouse compute, strict pre-load masking | Cloud warehouses with elastic compute: the modern default |
| Stage | Tools |
|---|---|
| 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 suites | Informatica, Talend, SSIS, IBM DataStage, Matillion |
| Orchestration | Airflow, Dagster, Prefect, Lakeflow Jobs, ADF, Step Functions |
| Reverse ETL | Hightouch, Census: push warehouse data back into CRMs and SaaS tools |
"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.
| Type | Behaviour | History | Use for |
|---|---|---|---|
| 0 | Never change | Original value kept | Date of birth, original signup channel |
| 1 | Overwrite | None | Corrections, attributes nobody analyses historically |
| 2 | New row per change, with validity dates | Full | Region, segment, anything reports group history by |
| 3 | Previous value in an extra column | One previous value | Before/after comparisons, e.g. a sales territory realignment |
| 4 | Current table + separate history table | Full, kept apart | Very fast-changing attributes |
| 6 | Type 2 rows + Type 1 "current" column on every row | Full + current view | Report 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_id | name | city |
|---|---|---|
| 1 | Asha | Mumbai |
| 2 | Ravi | Delhi |
| 3 | Meera | Chennai |
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_sk | customer_id | name | city | valid_from | valid_to | is_current |
|---|---|---|---|---|---|---|
| 1 | 1 | Asha | Pune | 2025-01-01 | 2026-02-28 | False |
| 3 | 1 | Asha | Mumbai | 2026-03-01 | NULL | True |
| 2 | 2 | Ravi | Delhi | 2025-01-01 | NULL | True |
| 4 | 3 | Meera | Chennai | 2026-03-01 | NULL | True |
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_id | name | city | previous_city | city_changed_on |
|---|---|---|---|---|
| 1 | Asha | Mumbai | Pune | 2026-03-01 |
| 2 | Ravi | Delhi | NULL | NULL |
"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.
"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
| Structure | How it helps | Where |
|---|---|---|
| B-tree index | Logarithmic lookup and range scans by key | OLTP databases |
| Composite index | Index on (a, b); usable for filters on a, or a and b (leftmost prefix rule) | OLTP databases |
| Covering index | Contains every column the query needs: no table lookup | OLTP, read-heavy queries |
| Clustered index | Table rows physically ordered by the key | SQL Server, MySQL InnoDB primary key |
| Bitmap index | Bit arrays for low-cardinality columns; fast AND/OR | Oracle warehouses |
| Zone maps / min-max statistics | Skip blocks whose min/max cannot match the filter | Parquet, Snowflake micro-partitions, Redshift blocks |
| Clustering keys / sort keys | Co-locate similar values so zone maps prune more | Snowflake clustering keys, Redshift sort keys, BigQuery clustering |
| Z-order / liquid clustering | Multi-column clustering for files | Delta 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}")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.
"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.
| Strategy | How | Strength | Risk |
|---|---|---|---|
| Range | Key ranges per shard (A–F, G–M ...) | Efficient range queries | Hot spots (all new rows on the last shard) |
| Hash | hash(key) mod N | Even distribution | Range queries hit every shard; adding a shard moves most keys |
| Consistent hashing | Keys and shards placed on a hash ring | Adding a shard moves only about 1/N of keys | More complex |
| Directory / geo | A lookup table maps key to shard | Flexible; data residency by region | The 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%}")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
| Lever | What to do |
|---|---|
| Read the plan | EXPLAIN / query profile: scans, joins, row estimates, spills |
| Prune data | Filter on partition and cluster columns; keep predicates sargable |
| Push down | Select only needed columns; filter before joins (projection and predicate pushdown) |
| Join strategy | Broadcast small tables; avoid many-to-many joins; pre-aggregate |
| Statistics | Keep table statistics fresh so the optimiser estimates well |
| Skew | Detect hot keys; salt or isolate them |
| Reuse | Materialized views, aggregate tables, result caching |
| Right-size compute | Separate warehouses or clusters per workload; scale for concurrency |
"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
| Strategy | What it means | Typical implementation |
|---|---|---|
| Lifecycle and tiering | Hot data on fast storage, cold data on cheap storage | S3 Standard → Infrequent Access → Glacier; BigQuery long-term storage pricing |
| Retention and archival | Keep data as long as needed and no longer | Retention policies per dataset; legal holds; purge jobs |
| Partitioning | Split large tables by date or key | Partitioned tables; partition expiry |
| Compaction and maintenance | Merge small files; remove obsolete versions | OPTIMIZE / VACUUM (Delta), rewrite_data_files / expire_snapshots (Iceberg) |
| Backup and recovery | Recover from mistakes and disasters | Time travel, snapshots, cross-region replication, tested restores |
| Data quality | Detect bad data before users do | Tests, expectations, quarantine, reconciliation |
| Metadata and governance | Know what data exists, who owns it, who may use it | Catalog, glossary, lineage, classification, access policies |
| Master and reference data | One version of core entities and codes | MDM hub, reference tables |
| Cost management | Pay for what is used | Auto-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.
"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."