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.

Intermediate 2 min readLesson 4 of 14

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

SQL
-- 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:

SQL
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

SQL
-- 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).

SQL
function_name(...) OVER (
    PARTITION BY ...     -- separate windows per group (optional)
    ORDER BY ...         -- order within the window
    ROWS BETWEEN ...     -- frame (optional)
)

Ranking

SQL
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;
salaryROW_NUMBERRANKDENSE_RANK
200111
180222
180322
150443

Top-N per group (a very common interview question):

SQL
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

SQL
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

SQL
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

SQL
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

SQL
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 only

Views 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:

SQL
-- 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 queries

Classic interview queries

ProblemTechnique
Nth highest salaryDENSE_RANK() or OFFSET n-1 LIMIT 1
Top N per groupROW_NUMBER()/DENSE_RANK() OVER (PARTITION BY …)
DuplicatesGROUP 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 growthLAG()
Running totalSUM() OVER (ORDER BY …)
Employees earning more than their managerSelf join
Customers without ordersNOT EXISTS
MedianPERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY …)
SQL
-- 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;
Key takeaways
  • 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.