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

Advanced SQL

Everything from advanced SELECT to window functions and recursive CTEs, with every query run on a sample database and its real result shown.

Contents
1. How SQL Really Runs, and Advanced SELECT 2. Joins 3. Sorting and Grouping 4. Aggregation 5. Common Table Expressions (CTEs) 6. Subqueries 7. Advanced String Functions and Regular Expressions 8. Window Functions 9. Recursive CTEs 10. Writing Fast SQL, and Interview Practice

1. How SQL Really Runs, and Advanced SELECT

SQL is written in one order but evaluated in another. Knowing the logical processing order explains most "why does this fail?" moments: why a column alias cannot be used in WHERE, why HAVING exists, and why window functions cannot appear in WHERE.

StepClauseWhat happens
1FROM / JOINBuild the working set of rows
2WHEREFilter individual rows (no aggregates, no aliases)
3GROUP BYCollapse rows into groups
4HAVINGFilter groups (aggregates allowed)
5Window functionsComputed over the remaining rows
6SELECTCompute expressions and aliases
7DISTINCTRemove duplicate result rows
8ORDER BYSort (aliases allowed here)
9LIMIT / OFFSETTrim the result

The sample database used on this page has customers, orders, employees, logins and app_logs. Every result below is real output from running the query.

NULL is "unknown", not a value

SQL uses three-valued logic: TRUE, FALSE and UNKNOWN. Any comparison with NULL is UNKNOWN, and WHERE keeps only TRUE rows. That is why city = NULL never matches and city <> 'Pune' silently drops the NULL city.

SELECT
  COUNT(*) FILTER (WHERE city <> 'Pune')                AS not_pune_naive,
  COUNT(*) FILTER (WHERE city IS DISTINCT FROM 'Pune')  AS not_pune_null_safe,
  COUNT(*) FILTER (WHERE city = NULL)                   AS equals_null,
  COUNT(*) FILTER (WHERE city IS NULL)                  AS is_null
FROM customers;
not_pune_naivenot_pune_null_safeequals_nullis_null
2301

CASE, COALESCE and NULLIF

SELECT order_id, amount,
       CASE WHEN status = 'DELIVERED' AND amount >= 100 THEN 'high value'
            WHEN status = 'DELIVERED'                    THEN 'standard'
            ELSE 'not revenue' END                       AS bucket,
       COALESCE(CAST(customer_id AS VARCHAR), 'guest')   AS customer,
       amount / NULLIF(0, 0)                             AS safe_divide
FROM orders
ORDER BY order_id
LIMIT 5;
order_idamountbucketcustomersafe_divide
101120.00high value1NULL
10280.00standard1NULL
103200.00not revenue2NULL
10450.00standard3NULL
105300.00high value3NULL

NULLIF(x, 0) turns a zero divisor into NULL, so the division returns NULL instead of failing. COALESCE returns the first non-NULL argument.

DISTINCT vs GROUP BY, and "latest row per key"

DISTINCT removes duplicate result rows. For "the latest order per customer" you need one whole row per key, which is a ranking problem (section 8). Some engines add a shortcut, DISTINCT ON in PostgreSQL and DuckDB:

SELECT DISTINCT ON (customer_id) customer_id, order_id, order_date, amount
FROM orders
WHERE customer_id IS NOT NULL
ORDER BY customer_id, order_date DESC;
customer_idorder_idorder_dateamount
11062026-03-1040.00
21072026-03-12150.00
31052026-03-09300.00
Say this in the interview

"SQL is evaluated FROM, WHERE, GROUP BY, HAVING, window functions, SELECT, DISTINCT, ORDER BY, LIMIT. That is why aliases are not visible in WHERE, why aggregates are filtered in HAVING, and why window results must be filtered in an outer query or with QUALIFY. And NULL comparisons are UNKNOWN, so I use IS NULL and IS DISTINCT FROM."

2. Joins

JoinReturnsTypical use
INNEROnly matching rowsFacts with their dimensions
LEFTAll left rows, NULLs where no matchKeep every customer, even without orders
FULL OUTERAll rows from both sidesReconciliation: what exists only on one side
SEMI (EXISTS / IN)Left rows that have a match, once eachCustomers who ordered
ANTI (NOT EXISTS)Left rows with no matchCustomers who never ordered
CROSSEvery combinationDate × store grids, scaffolding
SELFA table joined to itselfEmployee → manager

Anti join: customers with no delivered order

SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o
  WHERE o.customer_id = c.customer_id AND o.status = 'DELIVERED')
ORDER BY c.customer_id;
customer_idname
4John
5Sara

The LEFT JOIN filter trap

A condition on the right table placed in WHERE removes the NULL rows a LEFT JOIN created, quietly turning it into an INNER JOIN. Put right-side filters in the ON clause:

SELECT 'filter in WHERE' AS version, COUNT(DISTINCT c.customer_id) AS customers
FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'DELIVERED'
UNION ALL
SELECT 'filter in ON', COUNT(DISTINCT c.customer_id)
FROM customers c LEFT JOIN orders o
  ON o.customer_id = c.customer_id AND o.status = 'DELIVERED';
versioncustomers
filter in WHERE3
filter in ON5

With the filter in WHERE, John and Sara (no delivered orders) disappear and only 3 customers remain. With the filter in ON, all 5 customers are kept, with NULL order columns where nothing matched.

Self join: who reports to whom

SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.emp_id
ORDER BY e.emp_id;
employeemanager
NishaNULL
ArjunNisha
KiranArjun
LeelaArjun
VikramArjun
PoojaNisha
RahulPooja
TaraPooja

Join explosion: check cardinality before you trust totals

Joining on a key that is not unique on either side multiplies rows. Always know the expected cardinality (one-to-one, one-to-many, many-to-many) and verify it:

SELECT
  (SELECT COUNT(*) FROM orders)                                       AS order_rows,
  (SELECT COUNT(*) FROM orders o JOIN orders o2 ON o.customer_id = o2.customer_id) AS self_join_rows;
order_rowsself_join_rows
817

Orders joined to orders on customer_id is many-to-many: 8 order rows become 17 (customer 1 has 3 orders, so 3×3 = 9, plus 2×2 + 2×2 for customers 2 and 3; the NULL customer on order 108 matches nothing). The section "Joining Two Fact Tables" in the Enterprise Data Architect guide explains why this inflates sums.

NULL keys never match

Order 108 has a NULL customer_id. It disappears from every inner join, and from NOT IN logic (section 6). Decide explicitly how to treat unknown keys, for example by mapping them to an "unknown" dimension member.

Say this in the interview

"I pick the join by the question: INNER for matches, LEFT to keep the driving table, FULL for reconciliation, EXISTS and NOT EXISTS for semi and anti joins. I keep right-side filters in the ON clause of a LEFT JOIN, I check key uniqueness so joins don't explode, and I remember NULL keys never match."

3. Sorting and Grouping

GROUP BY collapses rows; every selected column must be grouped or aggregated. HAVING filters groups after aggregation. ORDER BY can use aliases and control where NULLs go.

SELECT COALESCE(city, '(unknown)') AS city, COUNT(*) AS customers
FROM customers
GROUP BY city
HAVING COUNT(*) >= 1
ORDER BY customers DESC, city NULLS LAST;
citycustomers
Pune2
(unknown)1
Delhi1
Mumbai1

Subtotals in one pass: ROLLUP, CUBE and GROUPING SETS

Reports often need detail rows and subtotals and a grand total. Instead of three queries joined with UNION ALL, use ROLLUP (hierarchical subtotals), CUBE (every combination) or GROUPING SETS (exactly the combinations you list). GROUPING(col) returns 1 on rows where that column was rolled up.

SELECT
  CASE WHEN GROUPING(status) = 1 THEN 'ALL' ELSE status END            AS status,
  CASE WHEN GROUPING(order_date) = 1 THEN 'ALL' ELSE CAST(order_date AS VARCHAR) END AS day,
  SUM(amount) AS revenue
FROM orders
WHERE order_date <= '2026-03-04'
GROUP BY ROLLUP (status, order_date)
ORDER BY GROUPING(status), status, GROUPING(order_date), day;
statusdayrevenue
CANCELLED2026-03-03200.00
CANCELLEDALL200.00
DELIVERED2026-03-01120.00
DELIVERED2026-03-0380.00
DELIVERED2026-03-0450.00
DELIVEREDALL250.00
ALLALL450.00

Sorting rules worth knowing

Say this in the interview

"GROUP BY collapses rows and HAVING filters groups. For subtotals I use ROLLUP, CUBE or GROUPING SETS with GROUPING() to label total rows, instead of UNION ALL. I always add a tie-breaker to ORDER BY and state NULLS FIRST or LAST, because default NULL ordering differs between databases."

4. Aggregation

FunctionCounts or computesNULL handling
COUNT(*)All rowsCounts NULL rows too
COUNT(col)Non-NULL values of colIgnores NULLs
COUNT(DISTINCT col)Distinct non-NULL valuesIgnores NULLs
SUM / AVG / MIN / MAXOver non-NULL valuesAVG divides by non-NULL count
SELECT COUNT(*)                    AS all_rows,
       COUNT(customer_id)          AS with_customer,
       COUNT(DISTINCT customer_id) AS distinct_customers,
       AVG(amount)                 AS avg_amount
FROM orders;
all_rowswith_customerdistinct_customersavg_amount
873126.875

Conditional aggregation: pivot in one pass

Instead of filtering several times, aggregate with a condition. FILTER (WHERE ...) is the standard form; SUM(CASE WHEN ... THEN x END) works everywhere.

SELECT customer_id,
       SUM(amount) FILTER (WHERE status = 'DELIVERED')            AS delivered,
       SUM(CASE WHEN status = 'CANCELLED' THEN amount ELSE 0 END) AS cancelled,
       COUNT(*) FILTER (WHERE status = 'RETURNED')                AS returns
FROM orders
WHERE customer_id IS NOT NULL
GROUP BY customer_id
ORDER BY customer_id;
customer_iddeliveredcancelledreturns
1200.000.001
2150.00200.000
3350.000.000

Medians, percentiles and lists

SELECT dept,
       COUNT(*)                                             AS people,
       AVG(salary)                                          AS mean_salary,
       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary)  AS median_salary,
       STRING_AGG(name, ', ' ORDER BY name)                 AS team
FROM employees
GROUP BY dept
ORDER BY dept;
deptpeoplemean_salarymedian_salaryteam
Engineering4160,000.00150,000.00Arjun, Kiran, Leela, Vikram
Exec1300,000.00300,000.00Nisha
Sales3121,666.6795,000.00Pooja, Rahul, Tara

Mean and median differ when data is skewed: averages hide outliers, medians resist them. On huge data, approximate functions such as APPROX_COUNT_DISTINCT (HyperLogLog) and APPROX_PERCENTILE are far cheaper and usually accurate to about 1–2%.

Say this in the interview

"COUNT(*) counts rows, COUNT(col) skips NULLs, and AVG divides by non-NULL values only. I pivot with conditional aggregation using FILTER or SUM(CASE ...), use PERCENTILE_CONT for medians, and approximate distinct counts and percentiles on very large tables."

5. Common Table Expressions (CTEs)

A CTE (WITH name AS (...)) names an intermediate result so a complex query reads top to bottom as steps. CTEs can reference earlier CTEs, which makes them ideal for pipelines: filter, then aggregate, then rank.

WITH delivered AS (
  SELECT customer_id, order_date, amount
  FROM orders
  WHERE status = 'DELIVERED' AND customer_id IS NOT NULL
),
per_customer AS (
  SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS revenue
  FROM delivered
  GROUP BY customer_id
)
SELECT c.name, p.orders, p.revenue,
       ROUND(100.0 * p.revenue / SUM(p.revenue) OVER (), 1) AS pct_of_total
FROM per_customer p
JOIN customers c USING (customer_id)
ORDER BY p.revenue DESC;
nameordersrevenuepct_of_total
Meera2350.0050.0
Asha2200.0028.6
Ravi1150.0021.4

CTE, subquery, temp table or view?

OptionLifetimeUse when
CTEOne statementReadability; step-by-step logic; recursion
SubqueryOne statementA small, single-use filter or value
Temp tableSessionA result reused by several statements, or worth indexing
ViewPermanent definitionLogic shared across users and tools
Materialized view / tablePermanent dataExpensive results read often

Whether a CTE is computed once or inlined into each reference depends on the engine (PostgreSQL 12+ inlines by default unless you write MATERIALIZED; Spark re-evaluates unless cached). Do not assume a CTE referenced twice runs once.

Say this in the interview

"I use CTEs to make queries read as named steps and to support recursion. They exist for one statement; for results reused across statements I use temp tables, and for shared logic a view. I don't assume a CTE is materialised: that depends on the engine."

6. Subqueries

KindReturnsExample
ScalarOne valuesalary > (SELECT AVG(salary) FROM employees)
Multi-rowA list for IN / ANYcustomer_id IN (SELECT ...)
CorrelatedRe-evaluated per outer rowCompare each employee to their own department
Derived tableA table in FROMFROM (SELECT ...) t

Correlated subquery: earning above the department average

SELECT name, dept, salary
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees x WHERE x.dept = e.dept)
ORDER BY dept, salary DESC;
namedeptsalary
ArjunEngineering220000
PoojaSales180000

Modern optimisers usually rewrite this into a join with a grouped subquery, but on some engines a correlated subquery runs once per row. A window function (AVG(salary) OVER (PARTITION BY dept)) expresses the same idea in one pass.

The NOT IN trap

If the subquery returns even one NULL, NOT IN returns no rows, because x NOT IN (1, NULL) means x <> 1 AND x <> NULL, and the second part is UNKNOWN. NOT EXISTS does not have this problem:

SELECT 'NOT IN' AS method, COUNT(*) AS customers_without_orders
FROM customers WHERE customer_id NOT IN (SELECT customer_id FROM orders)
UNION ALL
SELECT 'NOT EXISTS', COUNT(*)
FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
methodcustomers_without_orders
NOT IN0
NOT EXISTS2

Customers 4 and 5 have no orders, but NOT IN reports 0 because order 108 has a NULL customer_id.

Say this in the interview

"I use scalar subqueries for single values, EXISTS for semi joins and NOT EXISTS for anti joins, never NOT IN against a nullable column, because one NULL makes it return nothing. For per-group comparisons, a window function is usually clearer and faster than a correlated subquery."

7. Advanced String Functions and Regular Expressions

Raw data arrives as text: logs, file names, free-form addresses, JSON. Data engineers clean and parse it with string functions and regular expressions.

SELECT
  UPPER(TRIM('  pune '))                       AS upper_trim,
  SPLIT_PART('2026-03-01_sales_eu.csv', '_', 3) AS part_3,
  REPLACE('ravi@mail.com', '@mail.com', '')    AS user_name,
  CONCAT_WS('-', 'IN', 'MH', 'PUN')            AS code,
  LPAD(CAST(42 AS VARCHAR), 6, '0')            AS padded,
  'Mumbai' ILIKE 'mum%'                        AS case_insensitive_like;
upper_trimpart_3user_namecodepaddedcase_insensitive_like
PUNEeu.csvraviIN-MH-PUN000042True

Parsing log lines with regex

SELECT
  CAST(regexp_extract(line, '^(\S+ \S+)', 1) AS TIMESTAMP)  AS ts,
  regexp_extract(line, '(ERROR|WARN|INFO)', 1)               AS level,
  regexp_extract(line, '\[(\w+)\]', 1)                      AS service,
  CAST(regexp_extract(line, 'order=(\d+)', 1) AS INT)        AS order_id,
  regexp_replace(regexp_extract(line, 'user=(\S+)', 1),
                 '^(.).*@', '\1***@')                         AS user_masked,
  NULLIF(regexp_extract(line, 'code=(E\d+)', 1), '')          AS error_code
FROM app_logs
ORDER BY ts;
tslevelserviceorder_iduser_maskederror_code
2026-03-01 10:02:11ERRORpayments103r***@mail.comE502
2026-03-01 10:05:40INFOorders104m***@mail.comNULL
2026-03-01 10:07:02ERRORorders105m***@mail.comE404
2026-03-01 10:09:15WARNpayments107r***@mail.comNULL

The regex building blocks used above:

PatternMeaning
^ / $Start / end of string
\d, \w, \SDigit, word character, non-space
+, *, ?, {2,4}One or more, zero or more, optional, range
( )Capture group, returned by regexp_extract
[ ]Character class, e.g. [A-Z]
|Alternation: ERROR|WARN

Dialect map

TaskPostgreSQLSnowflakeBigQuerySpark SQL
Extractsubstring(s from 're')REGEXP_SUBSTRREGEXP_EXTRACTregexp_extract
Replaceregexp_replaceREGEXP_REPLACEREGEXP_REPLACEregexp_replace
Tests ~ 're'REGEXP_LIKEREGEXP_CONTAINSs RLIKE 're'

Regex is slow on big tables and hard to read. Parse once in silver, store the parsed columns, and keep patterns in one place with tests. Mask personal data such as emails before it reaches analytics layers.

Say this in the interview

"I clean text with TRIM, UPPER, SPLIT_PART and REPLACE, and parse semi-structured text such as logs with regexp_extract using capture groups. I parse once into typed columns in silver, mask personal data, and remember that regex function names differ across PostgreSQL, Snowflake, BigQuery and Spark."

8. Window Functions

A window function computes a value for each row using a set of related rows (the window), without collapsing rows like GROUP BY does. Syntax: func() OVER (PARTITION BY ... ORDER BY ... frame).

FamilyFunctionsUse
RankingROW_NUMBER, RANK, DENSE_RANK, NTILETop-N per group, deduplication, quartiles
OffsetLAG, LEAD, FIRST_VALUE, LAST_VALUE, NTH_VALUEPrevious/next row, change detection
AggregateSUM, AVG, COUNT, MIN, MAX OVER (...)Running totals, moving averages, share of total

ROW_NUMBER vs RANK vs DENSE_RANK

SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_number,
       RANK()       OVER (ORDER BY salary DESC) AS rank,
       DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees
WHERE dept = 'Engineering'
ORDER BY salary DESC, name;
namesalaryrow_numberrankdense_rank
Arjun220000111
Kiran150000222
Leela150000322
Vikram120000443

Kiran and Leela tie on 150,000: ROW_NUMBER breaks the tie arbitrarily, RANK leaves a gap (2, 2, 4), DENSE_RANK does not (2, 2, 3). For "Nth highest salary" use DENSE_RANK.

Top-N per group with QUALIFY

SELECT dept, name, salary
FROM employees
QUALIFY DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) <= 2
ORDER BY dept, salary DESC;
deptnamesalary
EngineeringArjun220000
EngineeringKiran150000
EngineeringLeela150000
ExecNisha300000
SalesPooja180000
SalesTara95000

Engineering returns three people because Kiran and Leela tie for second place; use ROW_NUMBER if you need exactly two. QUALIFY filters on a window result (Snowflake, BigQuery, Databricks, DuckDB). Elsewhere wrap the query: SELECT * FROM (... ) t WHERE rnk <= 2.

Running totals, moving averages and change from previous

WITH daily AS (
  SELECT order_date, SUM(amount) AS revenue
  FROM orders WHERE status = 'DELIVERED'
  GROUP BY order_date
)
SELECT order_date, revenue,
       SUM(revenue) OVER (ORDER BY order_date)                                   AS running_total,
       AVG(revenue) OVER (ORDER BY order_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_3,
       revenue - LAG(revenue) OVER (ORDER BY order_date)                         AS change_vs_prev
FROM daily
ORDER BY order_date;
order_daterevenuerunning_totalmoving_avg_3change_vs_prev
2026-03-01120.00120.00120.0NULL
2026-03-0380.00200.00100.0-40.00
2026-03-0450.00250.0083.3333-30.00
2026-03-09300.00550.00143.3333250.00
2026-03-12225.00775.00191.6667-75.00

Frames: ROWS vs RANGE

The frame decides which rows of the partition are included. ROWS counts physical rows; RANGE uses values, so ties on the ORDER BY value are included together. With ORDER BY and no frame, most engines default to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which surprises people when there are ties:

SELECT order_id, order_date, amount,
       SUM(amount) OVER (ORDER BY order_date)                                        AS default_range,
       SUM(amount) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frame
FROM orders
WHERE order_date BETWEEN '2026-03-01' AND '2026-03-04'
ORDER BY order_date, order_id;
order_idorder_dateamountdefault_rangerows_frame
1012026-03-01120.00120.00120.00
1022026-03-0380.00400.00200.00
1032026-03-03200.00400.00400.00
1042026-03-0450.00450.00450.00

Orders 102 and 103 share 3 March: the RANGE frame gives both the total including both (400); the ROWS frame adds them one at a time.

Gaps and islands: consecutive login streaks

A classic interview pattern. Subtracting a row number from the date gives the same "group key" for consecutive dates; each change in that key starts a new island:

WITH numbered AS (
  SELECT user_id, login_date,
         login_date - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS INT) AS grp
  FROM logins
)
SELECT user_id, MIN(login_date) AS streak_start, MAX(login_date) AS streak_end, COUNT(*) AS days
FROM numbered
GROUP BY user_id, grp
ORDER BY user_id, streak_start;
user_idstreak_startstreak_enddays
12026-03-012026-03-033
12026-03-062026-03-072
22026-03-012026-03-011
22026-03-032026-03-064
Say this in the interview

"Window functions compute per-row results over related rows without collapsing them. I use ROW_NUMBER for deduplication, DENSE_RANK for Nth-highest, LAG and LEAD for changes, and SUM OVER with an explicit ROWS frame for running totals and moving averages. I know the default frame is RANGE, which groups ties, and I filter window results with QUALIFY or an outer query. Gaps and islands is date minus row number."

9. Recursive CTEs

A recursive CTE has an anchor query (the starting rows) and a recursive query that joins back to the CTE, repeated until it returns no new rows. It solves hierarchies (org charts, bills of materials, folder trees), graph walks and series generation.

Org chart with level and path

WITH RECURSIVE org AS (
  SELECT emp_id, name, manager_id, 1 AS level, name AS path
  FROM employees
  WHERE manager_id IS NULL                       -- anchor: the top of the tree
  UNION ALL
  SELECT e.emp_id, e.name, e.manager_id, o.level + 1, o.path || ' > ' || e.name
  FROM employees e
  JOIN org o ON e.manager_id = o.emp_id          -- recursive step: direct reports
)
SELECT level, name, path
FROM org
ORDER BY path;
levelnamepath
1NishaNisha
2ArjunNisha > Arjun
3KiranNisha > Arjun > Kiran
3LeelaNisha > Arjun > Leela
3VikramNisha > Arjun > Vikram
2PoojaNisha > Pooja
3RahulNisha > Pooja > Rahul
3TaraNisha > Pooja > Tara

Total salary cost under each manager

WITH RECURSIVE reports AS (
  SELECT emp_id AS manager_id, emp_id, salary FROM employees
  UNION ALL
  SELECT r.manager_id, e.emp_id, e.salary
  FROM reports r JOIN employees e ON e.manager_id = r.emp_id
)
SELECT m.name AS manager, COUNT(*) - 1 AS people_below, SUM(r.salary) AS cost_incl_self
FROM reports r JOIN employees m ON m.emp_id = r.manager_id
GROUP BY m.name
HAVING COUNT(*) > 1
ORDER BY cost_incl_self DESC;
managerpeople_belowcost_incl_self
Nisha71305000
Arjun3640000
Pooja2365000

Date spine: fill missing days

Reports need a row for every day, even days with no sales. Generate the calendar recursively, then LEFT JOIN the facts:

WITH RECURSIVE days AS (
  SELECT DATE '2026-03-01' AS d
  UNION ALL
  SELECT d + 1 FROM days WHERE d < DATE '2026-03-06'
)
SELECT d AS day, COALESCE(SUM(o.amount), 0) AS revenue
FROM days
LEFT JOIN orders o ON o.order_date = d AND o.status = 'DELIVERED'
GROUP BY d
ORDER BY d;
dayrevenue
2026-03-01120.00
2026-03-020.00
2026-03-0380.00
2026-03-0450.00
2026-03-050.00
2026-03-060.00

Always include a stop condition (WHERE d < ..., a maximum level, or a visited-path check for graphs that may contain cycles). Without one, a cycle recurses until the engine's recursion limit stops it, or forever.

Say this in the interview

"A recursive CTE has an anchor and a recursive member joined back to the CTE, repeated until no new rows appear. I use it for hierarchies with level and path, for rolling costs up a tree, and for date spines. I always add a stop condition and cycle protection."

10. Writing Fast SQL, and Interview Practice

PracticeWhy
Filter early and select only needed columnsColumnar engines read only the columns you name; less data to shuffle
Keep predicates "sargable"WHERE order_date >= '2026-03-01' can use an index or partition pruning; WHERE YEAR(order_date) = 2026 often cannot
Aggregate before joiningJoin small results, not raw facts
Prefer EXISTS to IN for large subqueriesStops at the first match; no NULL trap with NOT EXISTS
Avoid functions on join keysPre-compute normalised keys in silver
Read the planEXPLAIN / EXPLAIN ANALYZE shows scans, joins and row estimates
Partition and cluster big tablesPrune files by date; co-locate rows by common filters
EXPLAIN SELECT customer_id, SUM(amount) FROM orders WHERE order_date >= '2026-03-05' GROUP BY customer_id;
Plan (DuckDB, read bottom to top)
┌───────────────────────────┐
│         PROJECTION        │
│    ────────────────────   │
│__internal_decompress_integ│
│     ral_integer(#0, 1)    │
│             #1            │
│                           │
│          ~0 rows          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│   PERFECT_HASH_GROUP_BY   │
│    ────────────────────   │
│         Groups: #0        │
│                           │
│        Aggregates:        │
│    sum_no_overflow(#1)    │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         PROJECTION        │
│    ────────────────────   │
│        customer_id        │
│           amount          │
│                           │
│           ~1 row          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         PROJECTION        │
│    ────────────────────   │
│__internal_compress_integra│
│     l_utinyint(#0, 1)     │
│             #1            │
│                           │
│           ~1 row          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│          SEQ_SCAN         │
│    ────────────────────   │
│           Table:          │
│     memory.main.orders    │
│                           │
│   Type: Sequential Scan   │
│                           │
│        Projections:       │
│        customer_id        │
│           amount          │
│                           │
│          Filters:         │
│ order_date>='2026-03-05': │
│           :DATE           │
│                           │
│           ~1 row          │
└───────────────────────────┘

Read the plan bottom-up. The SEQ_SCAN reads only the two columns the query needs (Projections: customer_id, amount) and applies the date filter inside the scan (Filters: order_date>=...), before the GROUP BY. That is projection and predicate pushdown.

Practice questions using this page's data

QuestionTechnique
Second-highest salary per departmentDENSE_RANK() with PARTITION BY, filter = 2
Remove duplicate rows keeping the latestROW_NUMBER() OVER (PARTITION BY key ORDER BY ts DESC) = 1
Customers who ordered in March but not AprilAnti join with NOT EXISTS
Month-over-month growthLAG over monthly aggregates
Longest login streak per userGaps and islands
All reports under a managerRecursive CTE
Revenue by city with subtotalsGROUP BY ROLLUP

Deep dive: the SQL Interview Questions guide covers this in more depth.