SQL ETL Pipelines: Staging, MERGE, and Quality Gates
A pipeline that only works when nothing goes wrong is not a pipeline. SQL alone â no Python required â can extract, transform, load, and refuse to publish bad data.
- Layered design â raw, staging, core, and mart tables with clear contracts
- Incremental loads â MERGE, ON CONFLICT, and watermark bookkeeping
- Slowly changing dimensions â Type 1 overwrites and Type 2 history done in SQL
- Quality gates â assertions that stop the run before bad rows ship Idempotency and loud failure are the two properties that separate toys from production ETL.
Prerequisites
- !Solid INSERT, UPDATE, and MERGE/ON CONFLICT knowledge
- !CTEs and window functions
- !Familiarity with transactions and locking basics
What You'll Learn
- 1Lay out a four-zone pipeline architecture and the contracts between layers
- 2Write idempotent incremental loads driven by a watermark timestamp
- 3Implement SCD Type 1 and Type 2 logic in set-based SQL
- 4Add data quality assertions that abort a run before publishing bad data
The Layered Contract
Production SQL pipelines almost universally settle into layers, each with a different owner and a different promise:
| Layer | Contents | Mutability | Owner promise |
|---|---|---|---|
| Raw | Byte-faithful landing of source extracts | Append-only | Nothing is edited; everything is replayable |
| Staging | Typed, cleaned, deduplicated working tables | Truncated or replaced per run | Shapes match contracts; failures stay here |
| Core | Conformed dimensions and facts | Carefully updated via MERGE/SCD | Business keys unique; history preserved per policy |
| Mart | Denormalized tables for dashboards and APIs | Rebuilt per refresh | Fast to query; numbers reconcile to core |
Each hop is a transformation with a testable contract. Raw preserves fidelity for audits and replays. Staging is where you fix data types, trim whitespace, normalize codes, and quarantine bad rows. Core holds the single source of truth for business concepts â customers, products, orders â with enforced keys. Marts optimize for reads and may happily denormalize.
Two rules keep this honest. First, never update raw; if a source re-sends a row, land a new version and resolve downstream. Second, every layer boundary has a row-count and checksum expectation you can assert before the next step runs.
Incremental Loads: Watermarks and Idempotency
Full refreshes are simple and correct until the source is large; then you need increments. The standard mechanism is a watermark: a timestamp or monotonically increasing key stored per pipeline, marking how far you have consumed. Each run reads only rows newer than the watermark, loads them, then advances the watermark in the same transaction as the load â never before, or a crash strands data; never after a partial failure, or you re-read.
Idempotency is the property that makes retries safe. If a run fails halfway and the orchestrator retries, the end state must equal the state a single successful run would have produced. With upserts keyed on natural business keys, re-processing the same batch is harmless: the second attempt overwrites identical values.
-- Incremental upsert driven by a watermark table (PostgreSQL flavor)
-- watermark(pipeline_name, last_loaded_at) holds the high-water mark
INSERT INTO staging.orders_staging
SELECT
o.order_id,
o.customer_id,
o.order_date,
o.status,
o.total,
now() AS loaded_at
FROM source.orders o
WHERE o.updated_at > (SELECT last_loaded_at FROM etl.watermark WHERE pipeline_name = 'orders')
AND o.updated_at <= now();
-- Upsert into core with natural key order_id; update all mutable columns
INSERT INTO core.orders AS co
(order_id, customer_id, order_date, status, total, updated_at)
SELECT s.order_id, s.customer_id, s.order_date, s.status, s.total, s.loaded_at
FROM staging.orders_staging s
ON CONFLICT (order_id) DO UPDATE
SET
customer_id = EXCLUDED.customer_id,
order_date = EXCLUDED.order_date,
status = EXCLUDED.status,
total = EXCLUDED.total,
updated_at = EXCLUDED.updated_at
WHERE co.updated_at < EXCLUDED.updated_at; -- guard against out-of-order replays
-- Advance the watermark only after the upsert succeeds, inside the same transaction
UPDATE etl.watermark
SET last_loaded_at = now()
WHERE pipeline_name = 'orders';
SQL Server equivalents use MERGE (with care â it has historically had concurrency pitfalls, so many teams prefer staged INSERT plus UPDATE) or a two-statement pattern. The watermark guard WHERE co.updated_at < EXCLUDED.updated_at is what protects you when a replay delivers an older version of a row after a newer one; without it, last-write-wins becomes last-arrival-wins, which is not the same thing.
Idempotent Backfills and Historical Replays
Backfills â reprocessing a historical window after a logic change or an upstream repair â are where non-idempotent pipelines reveal themselves. The safe pattern relies on the same upserts, plus three additions: a temporary watermark override, a batch isolation key, and row counts reconciled before and after.
Because the watermark normally prevents re-reading old rows, a backfill needs a scoped read: either a one-off query that selects the date window directly into staging, or a controlled rewind of the watermark executed under supervision. Load the window through the identical MERGE path used in incremental runs â never a special DELETE-then-INSERT variant â so the code path stays proven. Then compare row counts and checksums between source and core for the window, and only then advance the watermark back to its live position.
Replay safety also depends on transforms being deterministic. A transformation that stamps now() into a business column makes every replay produce different values; stamp load timestamps into separate lineage columns instead. Similarly, random sampling or shuffle-based deduplication must be seeded or eliminated. When the transformation is a pure function of its inputs, backfills are boring â and boring backfills are the goal: run them in off-peak windows, log before-and-after counts to etl.run_log, and require a second pair of eyes on the reconciliation output before closing the ticket.
Slowly Changing Dimensions in Set-Based SQL
Dimension tables change slowly â a customer moves, a product is renamed â and the business decides how much history to keep. Type 1 overwrites the attribute, keeping only current state. Type 2 keeps a row per version with validity dates, enabling point-in-time reporting.
-- SCD Type 2: close expired versions, open new ones, insert brand-new keys
WITH current_versions AS (
SELECT
customer_id,
region,
valid_from,
valid_to,
is_current
FROM core.dim_customer
WHERE is_current
),
source_rows AS (
SELECT DISTINCT ON (customer_id)
customer_id,
region
FROM staging.customers_staging
),
changes AS (
SELECT
s.customer_id,
s.region,
CURRENT_DATE AS new_valid_from
FROM source_rows s
LEFT JOIN current_versions c ON c.customer_id = s.customer_id
WHERE c.customer_id IS NULL -- brand-new key
OR c.region IS DISTINCT FROM s.region -- attribute changed
)
-- Close the old versions that are superseded
UPDATE core.dim_customer d
SET
valid_to = ch.new_valid_from - INTERVAL '1 day',
is_current = FALSE
FROM changes ch
WHERE d.customer_id = ch.customer_id
AND d.is_current;
-- Insert the new versions (new keys and changed attributes)
INSERT INTO core.dim_customer
(customer_id, region, valid_from, valid_to, is_current)
SELECT
ch.customer_id,
s.region,
ch.new_valid_from,
DATE '9999-12-31',
TRUE
FROM changes ch
INNER JOIN source_rows s ON s.customer_id = ch.customer_id;
The mechanics repeat in every SCD implementation: detect differences with IS DISTINCT FROM (NULL-safe comparison), close open rows, then insert successors with an open-ended valid_to. Point-in-time facts join on fact.order_date BETWEEN dim.valid_from AND dim.valid_to â or on precomputed surrogate keys when the fact table already carries them.
Late-arriving facts deserve a note: a January order landing in February's feed must join to the dimension version valid in January, which is exactly why Type 2 history exists. Design fact loads to look up versions by date, not by "current".
Quality Gates That Fail Loudly
The cheapest place to catch bad data is inside the pipeline, before the mart publishes. Codify expectations as assertions â queries that return rows when the data is wrong â and abort the run when they fire.
-- Assertion queries: each MUST return zero rows to pass
-- 1. Business key uniqueness
SELECT order_id, COUNT(*) AS n
FROM core.orders
GROUP BY order_id
HAVING COUNT(*) > 1;
-- 2. Referential integrity: facts must point at existing customers
SELECT f.order_id
FROM core.orders f
LEFT JOIN core.dim_customer d ON d.customer_id = f.customer_id AND d.is_current
WHERE d.customer_id IS NULL;
-- 3. Range sanity: totals cannot be negative; dates cannot be in the future
SELECT order_id, total, order_date
FROM core.orders
WHERE total < 0 OR order_date > CURRENT_DATE + INTERVAL '1 day';
-- 4. Freshness: the pipeline must have delivered data recently
SELECT pipeline_name
FROM etl.watermark
WHERE last_loaded_at < NOW() - INTERVAL '26 hours';
-- 5. Volume sanity: row count within 30% of the trailing average
WITH daily_counts AS (
SELECT loaded_at::date AS d, COUNT(*) AS n
FROM staging.orders_staging
GROUP BY loaded_at::date
),
recent_avg AS (
SELECT AVG(n) AS avg_n
FROM daily_counts
WHERE d < CURRENT_DATE
)
SELECT s.d, s.n, r.avg_n
FROM daily_counts s
CROSS JOIN recent_avg r
WHERE s.d = CURRENT_DATE
AND s.n < 0.7 * r.avg_n;
Wire these into the orchestrator: any non-zero result set aborts before the mart refresh, pages the owning team, and leaves the previous mart intact. A pipeline that silently publishes a 60 percent volume drop is worse than one that fails, because the failure gets diagnosed while the silent drop gets blamed on the business.
Wrap each run in a transaction (or a staging-table swap with ALTER TABLE ... RENAME for large marts) so failure leaves the published layer untouched. That single habit converts midnight incidents into morning investigations.
Orchestration Concerns Worth Knowing
Pure SQL pipelines still need operational scaffolding: a scheduler (Airflow, Dagster, cron with locks) that guarantees single-flight execution per pipeline; retry with backoff on transient failures; and run metadata â row counts, durations, watermarks â written to an etl.run_log table so regressions are visible. Idempotent steps make retries free. Watermark commits make replays precise. Assertions make both observable.
Keep the transformation logic in version-controlled SQL files executed by the orchestrator, not embedded in stored procedures that drift from the repository. Whether the runner is psql, dbt, or a thin wrapper script, the database objects you reviewed here â staging tables, watermark state, assertion queries â are the portable core of any SQL-first pipeline platform.
Common Mistakes
Advancing the watermark before the load commits
Fix: Move the watermark update into the same transaction as the upsert so crashes cannot strand rows
Using MERGE without handling out-of-order replays
Fix: Compare version or updated_at columns and skip stale arrivals explicitly
Truncating the mart before the replacement data is validated
Fix: Load into staging, assert, then swap via rename so readers always see a complete dataset
Type 2 dimensions without a point-in-time join strategy
Fix: Join facts on validity ranges or carry surrogate keys captured at fact-load time
Silent success on zero-row loads
Fix: Assert minimum volumes and freshness; a pipeline that loads nothing should alert
Best Practices
- Land raw data immutably; do all cleanup in staging
- Make every load idempotent so orchestrator retries are free
- Encode row counts and checksums at each layer boundary and log them
- Fail loudly: assertions before publication, never after
- Keep pipeline SQL in version control and review schema changes like code
Interview Questions
Q1: What makes an ETL load idempotent?
Re-running it produces the same end state as running it once. In SQL pipelines this usually means upserts keyed on natural business keys plus watermark guards that ignore stale versions.
Q2: How do you implement SCD Type 2 in SQL?
Detect changed attributes with NULL-safe comparison, close currently open rows by setting valid_to and is_current false, and insert new versions with an open-ended valid_to â typically in one transaction.
Q3: Where should data quality checks run?
At each layer boundary, before publication, as queries that return rows on violation. The orchestrator aborts the run on any violation and leaves the previous published dataset intact.
Key Takeaways
- Raw, staging, core, and mart layers each carry a different contract and owner promise
- Watermarks drive incremental loads; commit them with the data, never before
- Idempotent upserts make retries safe and replays boring
- SCD Type 2 is three set-based steps: detect, close, insert
- Assertions that fail loudly beat dashboards that notice a silent drop days later