Advanced SQL
Subqueries, CTEs and recursive CTEs, window functions (ROW_NUMBER, RANK, LAG, running totals), CASE, set operations, views, JSON and the classic interview queries.
Basic SQL filters, joins and aggregates. Advanced SQL lets you express rankings, running totals, comparisons with previous rows, hierarchies and multi-step logic in a single query, usually far faster than doing it in application code.
Subqueries
-- Scalar subquery: employees paid above the company average
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
-- Correlated subquery: above their own department's average
SELECT e.name, e.dept, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(salary) FROM employees x WHERE x.dept = e.dept);
-- Derived table in FROM
SELECT dept, avg_sal
FROM (SELECT dept, AVG(salary) AS avg_sal FROM employees GROUP BY dept) t
WHERE avg_sal > 100000;A correlated subquery refers to the outer row, so it's logically evaluated once per row. Optimisers often rewrite it into a join, but not always — check the plan.
Common table expressions (WITH)
CTEs name intermediate results, making long queries readable step by step:
WITH dept_stats AS (
SELECT dept, AVG(salary) AS avg_sal, COUNT(*) AS n
FROM employees
GROUP BY dept
),
big_depts AS (
SELECT * FROM dept_stats WHERE n >= 10
)
SELECT e.name, e.salary, b.avg_sal
FROM employees e
JOIN big_depts b ON b.dept = e.dept
WHERE e.salary > b.avg_sal;Recursive CTEs: hierarchies and graphs
-- Everyone who reports (directly or indirectly) to employee 1
WITH RECURSIVE reports AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees
WHERE manager_id = 1 -- anchor
UNION ALL
SELECT e.id, e.name, e.manager_id, r.depth + 1
FROM employees e
JOIN reports r ON e.manager_id = r.id -- recursive step
)
SELECT * FROM reports ORDER BY depth;The anchor seeds the result; the recursive part runs repeatedly on the rows produced last time until no new rows appear. Used for org charts, category trees, bill-of-materials, threaded comments and graph reachability.
Window functions
A window function computes a value across a set of related rows without collapsing them (unlike GROUP BY).
function_name(...) OVER (
PARTITION BY ... -- separate windows per group (optional)
ORDER BY ... -- order within the window
ROWS BETWEEN ... -- frame (optional)
)Ranking
SELECT name, dept, salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS drnk
FROM employees;| salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 200 | 1 | 1 | 1 |
| 180 | 2 | 2 | 2 |
| 180 | 3 | 2 | 2 |
| 150 | 4 | 4 | 3 |
Top-N per group (a very common interview question):
SELECT * FROM (
SELECT e.*, DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS r
FROM employees e
) t
WHERE r <= 3;Running totals and moving averages
SELECT day, revenue,
SUM(revenue) OVER (ORDER BY day) AS running_total,
AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_7d,
revenue * 100.0 / SUM(revenue) OVER () AS pct_of_total
FROM daily_sales;Comparing with neighbouring rows
SELECT day, revenue,
LAG(revenue) OVER (ORDER BY day) AS prev_day,
revenue - LAG(revenue) OVER (ORDER BY day) AS change,
LEAD(revenue) OVER (ORDER BY day) AS next_day,
FIRST_VALUE(revenue) OVER (ORDER BY day) AS first_day
FROM daily_sales;CASE expressions
SELECT name,
CASE
WHEN salary >= 150000 THEN 'senior'
WHEN salary >= 90000 THEN 'mid'
ELSE 'junior'
END AS band,
COUNT(*) FILTER (WHERE dept = 'Sales') OVER () AS sales_headcount -- Postgres
FROM employees;
-- Pivoting with conditional aggregation
SELECT dept,
SUM(CASE WHEN EXTRACT(YEAR FROM hired_on) = 2023 THEN 1 ELSE 0 END) AS hired_2023,
SUM(CASE WHEN EXTRACT(YEAR FROM hired_on) = 2024 THEN 1 ELSE 0 END) AS hired_2024
FROM employees
GROUP BY dept;Set operations
SELECT email FROM customers
UNION -- removes duplicates (UNION ALL keeps them and is faster)
SELECT email FROM newsletter_subscribers;
SELECT id FROM users INTERSECT SELECT user_id FROM orders; -- in both
SELECT id FROM users EXCEPT SELECT user_id FROM orders; -- in first onlyViews and materialised views
- A view is a saved query used like a table. It simplifies access and can restrict columns for security.
- A materialised view stores the result physically and must be refreshed. Great for expensive dashboards (
REFRESH MATERIALIZED VIEW CONCURRENTLY …).
JSON in SQL
Modern relational databases store and query semi-structured data:
-- PostgreSQL jsonb
SELECT payload->>'event' AS event, COUNT(*)
FROM events
WHERE payload @> '{"source": "mobile"}'
GROUP BY 1;
CREATE INDEX ON events USING GIN (payload); -- index containment queriesClassic interview queries
| Problem | Technique |
|---|---|
| Nth highest salary | DENSE_RANK() or OFFSET n-1 LIMIT 1 |
| Top N per group | ROW_NUMBER()/DENSE_RANK() OVER (PARTITION BY …) |
| Duplicates | GROUP BY … HAVING COUNT(*) > 1; delete with ROW_NUMBER() > 1 |
| Consecutive days / streaks ("gaps and islands") | date - ROW_NUMBER() is constant within a streak |
| Month-over-month growth | LAG() |
| Running total | SUM() OVER (ORDER BY …) |
| Employees earning more than their manager | Self join |
| Customers without orders | NOT EXISTS |
| Median | PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY …) |
-- Gaps and islands: longest login streak per user
WITH d AS (
SELECT DISTINCT user_id, login_date FROM logins
),
g AS (
SELECT user_id, login_date,
login_date - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date))::int AS grp
FROM d
)
SELECT user_id, MAX(cnt) AS longest_streak
FROM (SELECT user_id, grp, COUNT(*) AS cnt FROM g GROUP BY user_id, grp) s
GROUP BY user_id;- Subqueries can be scalar, correlated or derived tables; prefer EXISTS for existence checks.
- CTEs structure multi-step queries; recursive CTEs walk hierarchies and graphs.
- Window functions (ROW_NUMBER, RANK, LAG, SUM OVER) compute across rows without collapsing them.
- CASE plus aggregation pivots data; UNION ALL is cheaper than UNION.
- Materialised views cache expensive results; JSON columns handle semi-structured data.