5.1 Window Functions: OVER & PARTITION BY
Window function = calculation across a "window" of rows WITHOUT collapsing groups (unlike GROUP BY). OVER() — the entire table as one window. OVER(PARTITION BY dept) — separate window per department. OVER(ORDER BY salary) — ordered window. The concept: GROUP BY collapses rows, window functions keep ALL rows while computing aggregates alongside. This distinction is key.
5.2 Ranking: ROW_NUMBER, RANK, DENSE_RANK
ROW_NUMBER: 1,2,3,4,5 (no ties — arbitrary tiebreak). RANK: 1,2,2,4,5 (ties get same rank, gap after). DENSE_RANK: 1,2,2,3,4 (ties get same rank, no gap). "Find the top 3 highest-paid employees per department" = DENSE_RANK() OVER(PARTITION BY dept ORDER BY salary DESC) with WHERE rnk <= 3. THE most common window function interview question.
5.3 LEAD, LAG & Running Aggregates
LAG(col, offset): access previous row's value. LEAD(col, offset): access next row's value. "Find employees whose salary decreased from previous month" = WHERE salary < LAG(salary) OVER(ORDER BY month). Running totals: SUM(amount) OVER(ORDER BY date). Running average: AVG(amount) OVER(ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). Moving window calculations.
5.4 NTILE, FIRST_VALUE, LAST_VALUE
NTILE(n): divide rows into n equal groups (quartiles, deciles, percentiles). FIRST_VALUE / LAST_VALUE: get first/last value in window frame. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (default frame). Frame specification: ROWS vs RANGE. Practical: "Divide customers into 4 spending quartiles" = NTILE(4) OVER(ORDER BY total_spend).
5.5 Common Table Expressions (WITH clause)
WITH cte_name AS (SELECT ...) SELECT * FROM cte_name. CTEs make complex queries readable — name your intermediate steps. Multiple CTEs: WITH cte1 AS (...), cte2 AS (...) SELECT ... CTEs vs subqueries: CTEs are reusable within the query (reference a CTE multiple times). CTEs vs views: CTEs are query-scoped (don't persist). When CTE makes a query 10x more readable.
5.6 Recursive CTEs
WITH RECURSIVE for hierarchical data: employee org chart (manager → reports), category trees (parent → children), bill of materials. Structure: base case UNION ALL recursive step. "Find all subordinates of a manager" = recursive CTE traversing the org chart. Also: generate date sequences, number series. Recursive CTEs replace what would need procedural code in most other approaches.
Placement relevance: Window functions are NOW the most tested advanced SQL topic — Amazon, Flipkart, Goldman Sachs, and every analytics firm test RANK/DENSE_RANK/ROW_NUMBER + PARTITION BY extensively. "Find top N per group" is the template question. CTEs appear in every complex SQL interview question. These topics separate "basic SQL" from "I can get hired as a data analyst."