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.
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.
| Step | Clause | What happens |
|---|---|---|
| 1 | FROM / JOIN | Build the working set of rows |
| 2 | WHERE | Filter individual rows (no aggregates, no aliases) |
| 3 | GROUP BY | Collapse rows into groups |
| 4 | HAVING | Filter groups (aggregates allowed) |
| 5 | Window functions | Computed over the remaining rows |
| 6 | SELECT | Compute expressions and aliases |
| 7 | DISTINCT | Remove duplicate result rows |
| 8 | ORDER BY | Sort (aliases allowed here) |
| 9 | LIMIT / OFFSET | Trim 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_naive | not_pune_null_safe | equals_null | is_null |
|---|---|---|---|
| 2 | 3 | 0 | 1 |
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_id | amount | bucket | customer | safe_divide |
|---|---|---|---|---|
| 101 | 120.00 | high value | 1 | NULL |
| 102 | 80.00 | standard | 1 | NULL |
| 103 | 200.00 | not revenue | 2 | NULL |
| 104 | 50.00 | standard | 3 | NULL |
| 105 | 300.00 | high value | 3 | NULL |
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_id | order_id | order_date | amount |
|---|---|---|---|
| 1 | 106 | 2026-03-10 | 40.00 |
| 2 | 107 | 2026-03-12 | 150.00 |
| 3 | 105 | 2026-03-09 | 300.00 |
"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
| Join | Returns | Typical use |
|---|---|---|
| INNER | Only matching rows | Facts with their dimensions |
| LEFT | All left rows, NULLs where no match | Keep every customer, even without orders |
| FULL OUTER | All rows from both sides | Reconciliation: what exists only on one side |
| SEMI (EXISTS / IN) | Left rows that have a match, once each | Customers who ordered |
| ANTI (NOT EXISTS) | Left rows with no match | Customers who never ordered |
| CROSS | Every combination | Date × store grids, scaffolding |
| SELF | A table joined to itself | Employee → 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_id | name |
|---|---|
| 4 | John |
| 5 | Sara |
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';
| version | customers |
|---|---|
| filter in WHERE | 3 |
| filter in ON | 5 |
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;
| employee | manager |
|---|---|
| Nisha | NULL |
| Arjun | Nisha |
| Kiran | Arjun |
| Leela | Arjun |
| Vikram | Arjun |
| Pooja | Nisha |
| Rahul | Pooja |
| Tara | Pooja |
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_rows | self_join_rows |
|---|---|
| 8 | 17 |
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.
"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;
| city | customers |
|---|---|
| Pune | 2 |
| (unknown) | 1 |
| Delhi | 1 |
| Mumbai | 1 |
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;
| status | day | revenue |
|---|---|---|
| CANCELLED | 2026-03-03 | 200.00 |
| CANCELLED | ALL | 200.00 |
| DELIVERED | 2026-03-01 | 120.00 |
| DELIVERED | 2026-03-03 | 80.00 |
| DELIVERED | 2026-03-04 | 50.00 |
| DELIVERED | ALL | 250.00 |
| ALL | ALL | 450.00 |
Sorting rules worth knowing
- Without
ORDER BY, row order is not guaranteed, even if it looks stable - Make sorts deterministic with a tie-breaker, such as
ORDER BY amount DESC, order_id, or pagination will repeat and skip rows - NULLs sort last ascending in PostgreSQL, Oracle and Snowflake but first in SQL Server and MySQL; say
NULLS FIRST/LASTexplicitly - Sorting is expensive on big data (a full shuffle in Spark); sort only for the final output or a window that needs it
"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
| Function | Counts or computes | NULL handling |
|---|---|---|
| COUNT(*) | All rows | Counts NULL rows too |
| COUNT(col) | Non-NULL values of col | Ignores NULLs |
| COUNT(DISTINCT col) | Distinct non-NULL values | Ignores NULLs |
| SUM / AVG / MIN / MAX | Over non-NULL values | AVG 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_rows | with_customer | distinct_customers | avg_amount |
|---|---|---|---|
| 8 | 7 | 3 | 126.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_id | delivered | cancelled | returns |
|---|---|---|---|
| 1 | 200.00 | 0.00 | 1 |
| 2 | 150.00 | 200.00 | 0 |
| 3 | 350.00 | 0.00 | 0 |
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;| dept | people | mean_salary | median_salary | team |
|---|---|---|---|---|
| Engineering | 4 | 160,000.00 | 150,000.00 | Arjun, Kiran, Leela, Vikram |
| Exec | 1 | 300,000.00 | 300,000.00 | Nisha |
| Sales | 3 | 121,666.67 | 95,000.00 | Pooja, 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%.
"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;| name | orders | revenue | pct_of_total |
|---|---|---|---|
| Meera | 2 | 350.00 | 50.0 |
| Asha | 2 | 200.00 | 28.6 |
| Ravi | 1 | 150.00 | 21.4 |
CTE, subquery, temp table or view?
| Option | Lifetime | Use when |
|---|---|---|
| CTE | One statement | Readability; step-by-step logic; recursion |
| Subquery | One statement | A small, single-use filter or value |
| Temp table | Session | A result reused by several statements, or worth indexing |
| View | Permanent definition | Logic shared across users and tools |
| Materialized view / table | Permanent data | Expensive 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.
"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
| Kind | Returns | Example |
|---|---|---|
| Scalar | One value | salary > (SELECT AVG(salary) FROM employees) |
| Multi-row | A list for IN / ANY | customer_id IN (SELECT ...) |
| Correlated | Re-evaluated per outer row | Compare each employee to their own department |
| Derived table | A table in FROM | FROM (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;
| name | dept | salary |
|---|---|---|
| Arjun | Engineering | 220000 |
| Pooja | Sales | 180000 |
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);
| method | customers_without_orders |
|---|---|
| NOT IN | 0 |
| NOT EXISTS | 2 |
Customers 4 and 5 have no orders, but NOT IN reports 0 because order 108 has a NULL customer_id.
"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_trim | part_3 | user_name | code | padded | case_insensitive_like |
|---|---|---|---|---|---|
| PUNE | eu.csv | ravi | IN-MH-PUN | 000042 | True |
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;| ts | level | service | order_id | user_masked | error_code |
|---|---|---|---|---|---|
| 2026-03-01 10:02:11 | ERROR | payments | 103 | r***@mail.com | E502 |
| 2026-03-01 10:05:40 | INFO | orders | 104 | m***@mail.com | NULL |
| 2026-03-01 10:07:02 | ERROR | orders | 105 | m***@mail.com | E404 |
| 2026-03-01 10:09:15 | WARN | payments | 107 | r***@mail.com | NULL |
The regex building blocks used above:
| Pattern | Meaning |
|---|---|
^ / $ | Start / end of string |
\d, \w, \S | Digit, 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
| Task | PostgreSQL | Snowflake | BigQuery | Spark SQL |
|---|---|---|---|---|
| Extract | substring(s from 're') | REGEXP_SUBSTR | REGEXP_EXTRACT | regexp_extract |
| Replace | regexp_replace | REGEXP_REPLACE | REGEXP_REPLACE | regexp_replace |
| Test | s ~ 're' | REGEXP_LIKE | REGEXP_CONTAINS | s 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.
"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).
| Family | Functions | Use |
|---|---|---|
| Ranking | ROW_NUMBER, RANK, DENSE_RANK, NTILE | Top-N per group, deduplication, quartiles |
| Offset | LAG, LEAD, FIRST_VALUE, LAST_VALUE, NTH_VALUE | Previous/next row, change detection |
| Aggregate | SUM, 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;| name | salary | row_number | rank | dense_rank |
|---|---|---|---|---|
| Arjun | 220000 | 1 | 1 | 1 |
| Kiran | 150000 | 2 | 2 | 2 |
| Leela | 150000 | 3 | 2 | 2 |
| Vikram | 120000 | 4 | 4 | 3 |
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;
| dept | name | salary |
|---|---|---|
| Engineering | Arjun | 220000 |
| Engineering | Kiran | 150000 |
| Engineering | Leela | 150000 |
| Exec | Nisha | 300000 |
| Sales | Pooja | 180000 |
| Sales | Tara | 95000 |
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_date | revenue | running_total | moving_avg_3 | change_vs_prev |
|---|---|---|---|---|
| 2026-03-01 | 120.00 | 120.00 | 120.0 | NULL |
| 2026-03-03 | 80.00 | 200.00 | 100.0 | -40.00 |
| 2026-03-04 | 50.00 | 250.00 | 83.3333 | -30.00 |
| 2026-03-09 | 300.00 | 550.00 | 143.3333 | 250.00 |
| 2026-03-12 | 225.00 | 775.00 | 191.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_id | order_date | amount | default_range | rows_frame |
|---|---|---|---|---|
| 101 | 2026-03-01 | 120.00 | 120.00 | 120.00 |
| 102 | 2026-03-03 | 80.00 | 400.00 | 200.00 |
| 103 | 2026-03-03 | 200.00 | 400.00 | 400.00 |
| 104 | 2026-03-04 | 50.00 | 450.00 | 450.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_id | streak_start | streak_end | days |
|---|---|---|---|
| 1 | 2026-03-01 | 2026-03-03 | 3 |
| 1 | 2026-03-06 | 2026-03-07 | 2 |
| 2 | 2026-03-01 | 2026-03-01 | 1 |
| 2 | 2026-03-03 | 2026-03-06 | 4 |
"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;
| level | name | path |
|---|---|---|
| 1 | Nisha | Nisha |
| 2 | Arjun | Nisha > Arjun |
| 3 | Kiran | Nisha > Arjun > Kiran |
| 3 | Leela | Nisha > Arjun > Leela |
| 3 | Vikram | Nisha > Arjun > Vikram |
| 2 | Pooja | Nisha > Pooja |
| 3 | Rahul | Nisha > Pooja > Rahul |
| 3 | Tara | Nisha > 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;
| manager | people_below | cost_incl_self |
|---|---|---|
| Nisha | 7 | 1305000 |
| Arjun | 3 | 640000 |
| Pooja | 2 | 365000 |
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;
| day | revenue |
|---|---|
| 2026-03-01 | 120.00 |
| 2026-03-02 | 0.00 |
| 2026-03-03 | 80.00 |
| 2026-03-04 | 50.00 |
| 2026-03-05 | 0.00 |
| 2026-03-06 | 0.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.
"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
| Practice | Why |
|---|---|
| Filter early and select only needed columns | Columnar 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 joining | Join small results, not raw facts |
| Prefer EXISTS to IN for large subqueries | Stops at the first match; no NULL trap with NOT EXISTS |
| Avoid functions on join keys | Pre-compute normalised keys in silver |
| Read the plan | EXPLAIN / EXPLAIN ANALYZE shows scans, joins and row estimates |
| Partition and cluster big tables | Prune 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;
┌───────────────────────────┐ │ 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
| Question | Technique |
|---|---|
| Second-highest salary per department | DENSE_RANK() with PARTITION BY, filter = 2 |
| Remove duplicate rows keeping the latest | ROW_NUMBER() OVER (PARTITION BY key ORDER BY ts DESC) = 1 |
| Customers who ordered in March but not April | Anti join with NOT EXISTS |
| Month-over-month growth | LAG over monthly aggregates |
| Longest login streak per user | Gaps and islands |
| All reports under a manager | Recursive CTE |
| Revenue by city with subtotals | GROUP BY ROLLUP |
Deep dive: the SQL Interview Questions guide covers this in more depth.