The scenario
Every hour, ShopKart's app dumps order changes into a staging table. It's messy, as real staging data always is:
-- Raw rows from the app, loaded every hour. The same order can arrive more than once.
CREATE TABLE staging_orders (
order_id INT, customer_id INT, status TEXT, amount NUMERIC(10, 2), updated_at TIMESTAMP
);
INSERT INTO staging_orders VALUES
(201, 1, 'PLACED', 2598, '2026-06-01 09:00'),
(201, 1, 'DELIVERED', 2598, '2026-06-02 18:30'), -- same order, newer status
(202, 3, 'PLACED', 4999, '2026-06-01 11:15'),
(202, 3, 'PLACED', 4999, '2026-06-01 11:15'), -- exact duplicate
(203, 4, 'CANCELLED', 499, '2026-06-01 12:00');📥staging_orders
Raw, duplicates, many versions
🧹De-duplicate
Latest version per order
🔁MERGE
Only rows after the watermark
📌Move watermark
Remember how far we got
✅Quality checks
Fail loudly if something's off
1. Find and remove duplicates
SELECT order_id, COUNT(*) AS copies
FROM staging_orders
GROUP BY order_id
HAVING COUNT(*) > 1
ORDER BY order_id;| order_id | copies |
|---|---|
| 201 | 2 |
| 202 | 2 |
WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) AS rn
FROM staging_orders
)
SELECT order_id, customer_id, status, amount, updated_at
FROM ranked
WHERE rn = 1
ORDER BY order_id;| order_id | customer_id | status | amount | updated_at |
|---|---|---|---|---|
| 201 | 1 | DELIVERED | 2598.00 | 2026-06-02 18:30:00 |
| 202 | 3 | PLACED | 4999.00 | 2026-06-01 11:15:00 |
| 203 | 4 | CANCELLED | 499.00 | 2026-06-01 12:00:00 |
Order 201 keeps its newest version (DELIVERED); order 202's exact duplicate collapses to one row. If two copies can share the same timestamp, add a tie-breaker (like an ingestion id) to the ORDER BY.
2. Incremental, idempotent load with a watermark
CREATE TABLE fact_orders (
order_id INT PRIMARY KEY, customer_id INT, status TEXT, amount NUMERIC(10, 2), updated_at TIMESTAMP
);
-- Remembers how far we have loaded
CREATE TABLE etl_watermark (table_name TEXT PRIMARY KEY, loaded_until TIMESTAMP);
INSERT INTO etl_watermark VALUES ('fact_orders', '1900-01-01');-- Idempotent incremental load: only new rows, latest version per order, safe to re-run
MERGE INTO fact_orders AS t
USING (
SELECT order_id, customer_id, status, amount, updated_at
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) AS rn
FROM staging_orders
WHERE updated_at > (SELECT loaded_until FROM etl_watermark WHERE table_name = 'fact_orders')
) x
WHERE rn = 1
) AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN
UPDATE SET status = s.status, amount = s.amount, updated_at = s.updated_at
WHEN NOT MATCHED THEN
INSERT VALUES (s.order_id, s.customer_id, s.status, s.amount, s.updated_at);
UPDATE etl_watermark
SET loaded_until = (SELECT MAX(updated_at) FROM staging_orders)
WHERE table_name = 'fact_orders';
SELECT * FROM fact_orders ORDER BY order_id;| order_id | customer_id | status | amount | updated_at |
|---|---|---|---|---|
| 201 | 1 | DELIVERED | 2598.00 | 2026-06-02 18:30:00 |
| 202 | 3 | PLACED | 4999.00 | 2026-06-01 11:15:00 |
| 203 | 4 | CANCELLED | 499.00 | 2026-06-01 12:00:00 |
- Only new rows:
updated_at > loaded_until, so each run reads a small slice. - One row per key: de-duplicated inside the MERGE source (MERGE fails if two source rows match one target row).
- Only if newer:
WHEN MATCHED AND s.updated_at > t.updated_at, so late, older copies never overwrite newer data. - Idempotent: we ran the MERGE a second time and still had exactly 3 rows.
3. Gaps and islands: streaks
-- Login streaks: consecutive dates minus their row number give the same "group" date
WITH numbered AS (
SELECT customer_id, login_date,
login_date - (ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY login_date))::int AS grp
FROM logins
)
SELECT customer_id,
MIN(login_date) AS streak_start,
MAX(login_date) AS streak_end,
COUNT(*) AS days
FROM numbered
GROUP BY customer_id, grp
ORDER BY customer_id, streak_start;| customer_id | streak_start | streak_end | days |
|---|---|---|---|
| 1 | 2026-04-01 | 2026-04-03 | 3 |
| 1 | 2026-04-05 | 2026-04-06 | 2 |
| 2 | 2026-04-01 | 2026-04-01 | 1 |
| 2 | 2026-04-03 | 2026-04-06 | 4 |
| 3 | 2026-04-02 | 2026-04-02 | 1 |
| login_date | row_number | date − row_number |
|---|---|---|
| Apr 1 | 1 | Mar 31 |
| Apr 2 | 2 | Mar 31 |
| Apr 3 | 3 | Mar 31 ← same: one streak |
| Apr 5 | 4 | Apr 1 ← new group: a gap happened |
| Apr 6 | 5 | Apr 1 |
Consecutive dates rise by 1, and so does the row number, so their difference stays constant inside a streak. Group by it.
4. Pivot rows into columns
SELECT p.category,
SUM(CASE WHEN o.order_date < '2026-05-01' THEN oi.quantity * oi.unit_price ELSE 0 END) AS april,
SUM(CASE WHEN o.order_date >= '2026-05-01' THEN oi.quantity * oi.unit_price ELSE 0 END) AS may
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status = 'DELIVERED'
GROUP BY p.category;| category | april | may |
|---|---|---|
| Accessories | 4192.00 | 4992.00 |
| Electronics | 13996.00 | 13996.00 |
5. Date spine: show the days with nothing
-- Every day in the range, even days with no orders (show 0, not a missing row)
WITH days AS (
SELECT d::date AS day
FROM generate_series(DATE '2026-04-01', DATE '2026-04-07', INTERVAL '1 day') AS d
)
SELECT days.day, COUNT(o.order_id) AS orders
FROM days
LEFT JOIN orders o ON o.order_date = days.day
GROUP BY days.day
ORDER BY days.day;| day | orders |
|---|---|
| 2026-04-01 | 2 |
| 2026-04-02 | 0 |
| 2026-04-03 | 1 |
| 2026-04-04 | 0 |
| 2026-04-05 | 1 |
| 2026-04-06 | 0 |
| 2026-04-07 | 1 |
Without the spine, April 2, 4 and 6 would simply be missing, and charts would draw misleading lines. PostgreSQL uses generate_series; Snowflake uses GENERATOR, Databricks sequence() + explode, or a permanent dim_date table (lesson 9).
6. Data quality checks
SELECT 'orders without a customer' AS check_name,
COUNT(*) AS failures
FROM orders o LEFT JOIN customers c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL
UNION ALL
SELECT 'customers with no city', COUNT(*) FROM customers WHERE city IS NULL
UNION ALL
SELECT 'duplicate order ids in staging', COUNT(*) - COUNT(DISTINCT order_id) FROM staging_orders
UNION ALL
SELECT 'items with price <= 0', COUNT(*) FROM order_items WHERE unit_price <= 0;| check_name | failures |
|---|---|
| orders without a customer | 0 |
| customers with no city | 1 |
| duplicate order ids in staging | 2 |
| items with price <= 0 | 0 |
Each check returns a failure count. A pipeline runs these after loading and stops (or alerts) when a must-be-zero check isn't zero. Tools like dbt tests and Databricks expectations are built on exactly these queries.
| Check | SQL idea |
|---|---|
| Uniqueness | COUNT(*) − COUNT(DISTINCT key) = 0 |
| Not null | COUNT(*) WHERE col IS NULL = 0 |
| Referential integrity | LEFT JOIN parent … WHERE parent.key IS NULL = 0 |
| Accepted values | COUNT(*) WHERE status NOT IN (…) = 0 |
| Freshness | MAX(updated_at) > now() − interval '2 hours' |
| Volume | Today's row count within ±30% of the 7-day average |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you design an incremental load?1–3 yrs+
Q2How do you find duplicate rows and delete all but one?1–3 yrs+
Q3Find each user's longest login streak.3+ yrs+
Q4What data quality checks would you put on a fact table?3+ yrs+
Q5How do you make a full-refresh table load safe for readers?3+ yrs+
Key takeaways
- ✓Staging data is messy: de-duplicate deliberately.
- ✓Watermark + idempotent MERGE = reliable incremental loads.
- ✓Gaps-and-islands, pivots and date spines solve common reporting problems.
- ✓Quality checks turn silent data bugs into loud failures.
Frequently asked questions
What is an incremental load?
Loading only data that is new or changed since the last run, instead of reloading everything. A watermark (like the latest updated_at already loaded) tells the job where to start.
What does idempotent mean for a SQL pipeline?
Running the same load twice gives the same result as running it once: no duplicates, no double counting. MERGE on a key with an 'only if newer' condition makes loads idempotent.
What is the gaps and islands problem?
Finding runs of consecutive values (islands) and the breaks between them (gaps), like login streaks or periods a sensor was online. The classic trick subtracts ROW_NUMBER from the date.
How do I pivot rows into columns in SQL?
Conditional aggregation works everywhere: SUM(CASE WHEN month = 'Apr' THEN revenue END) AS april. Some databases (Snowflake, Databricks, SQL Server) also have a PIVOT clause.
What is a date spine?
A table or CTE with every date in a range. LEFT JOIN your facts onto it so days with no data appear as 0 instead of being missing.
🧠 Quick check: data engineering SQL patterns
1. Keep the newest copy of each order from a staging table. Use...
2. A watermark stores...
3. Consecutive dates minus their ROW_NUMBER give...
4. Days with no orders are missing from your daily report. Fix?
Checking your access…