# Topic 46: Window Functions
OVER, PARTITION BY, ORDER BY frame bounds, ROW_NUMBER, RANK, DENSE_RANK, and preserving row identities.
1. Definition
A Window Function performs a calculation across a set of table rows that are related to the current row, without collapsing the rows into a single summary output like GROUP BY does.
2. Explain Like I'm 5
GROUP BY merges an entire class into a single average score row. A Window Function gives each student their own report card showing their individual score AND the class average side-by-side.
3. Animation & Visual Simulation
Interactive Engine TraceWindow Functions Visual Simulator
WITH ranked_orders AS (
SELECT user_id, id, amount,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY amount DESC) AS rn
FROM orders
)
SELECT * FROM ranked_orders WHERE rn = 1;Active InputStep 1: Input & Parsing Stage
Initiating Window Functions
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Ranking employees by salary within each department while retaining all individual employee rows.
| Name | Dept | Salary | ROW_NUMBER() | RANK() | DENSE_RANK() |
|---|---|---|---|---|---|
| Alice | Eng | $120,000 | 1 | 1 | 1 |
| Bob | Eng | $120,000 | 2 | 1 | 1 |
| Charlie | Eng | $90,000 | 3 | 3 | 2 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank_in_dept, AVG(salary) OVER (PARTITION BY department) AS dept_avg_salary FROM employees;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| No Row Collapsing | Unlike GROUP BY, window functions retain the exact same number of rows as the input query. |
| WHERE Clause Restriction | Window functions are evaluated in the SELECT projection step and CANNOT be placed in WHERE or HAVING. |
| Default Frame Specification | An ORDER BY inside OVER() defaults to: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. |
| Evaluation order (after WHERE/HAVING) | Window functions evaluate at Step 5.5 (during SELECT); they cannot be used inside WHERE or HAVING clauses. |
| PARTITION BY vs GROUP BY | GROUP BY collapses multiple rows into a single row; PARTITION BY calculates aggregates while preserving all individual rows. |
7. Deep Dive: ROW_NUMBER() vs RANK() vs DENSE_RANK()
When two rows have identical sorting values (a tie): 1) ROW_NUMBER() assigns strictly sequential numbers (1, 2, 3), breaking ties arbitrarily. 2) RANK() assigns identical numbers but creates gaps (1, 1, 3). 3) DENSE_RANK() assigns identical numbers without gaps (1, 1, 2).
-- Ranking comparison on identical values [100, 100, 80]: ROW_NUMBER: 1, 2, 3 RANK: 1, 1, 3 (Gap created!) DENSE_RANK: 1, 1, 2 (No gap!)
8. Advantages & Disadvantages
Advantages
- •Computes complex running totals, rankings, and comparisons without multiple self-joins.
- •Retains full individual row context alongside aggregated metrics.
Disadvantages & Trade-offs
- •Window sorting on massive tables without matching indexes requires high memory in work_mem.
9. Common Interview Questions
Q1.What is the fundamental difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?
All three assign rankings based on ORDER BY within a partition: 1. ROW_NUMBER(): strictly sequential unique integers (1, 2, 3, 4); never assigns duplicate ranks even on ties. 2. RANK(): assigns identical ranks to tied rows and SKIPS subsequent rank numbers (1, 2, 2, 4); gap appears. 3. DENSE_RANK(): assigns identical ranks to tied rows and does NOT skip numbers (1, 2, 2, 3); no gaps.
| Score | ROW_NUMBER() | RANK() | DENSE_RANK() |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 95 | 2 | 2 | 2 |
| 95 | 3 | 2 | 2 |
| 90 | 4 | 4 | 3 |
| 85 | 5 | 5 | 4 |
Q2.Why can Window Functions NOT be used in the WHERE or HAVING clauses?
Because of the logical query processing order. WHERE evaluates at Step 2 to filter rows from disk, and HAVING evaluates at Step 4 to filter groups. Window functions are evaluated at Step 5.5, AFTER grouping, aggregation, and filtering have completed. To filter on a window function result, you must wrap the query in a Common Table Expression (CTE) or derived table.
Q3.How do you write a query to find the "Top 3 highest-earning employees in every department"?
You assign DENSE_RANK() partitioned by department and ordered by salary descending inside a CTE, then filter WHERE rnk <= 3 in the outer query:
WITH ranked_employees AS (
SELECT
id, name, department_id, salary,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees
)
SELECT id, name, department_id, salary, salary_rank
FROM ranked_employees
WHERE salary_rank <= 3
ORDER BY department_id, salary_rank;Q4.What is the performance and memory cost of executing a Window Function?
The engine must partition and sort rows in memory according to the OVER (PARTITION BY ... ORDER BY ...) clause. If input data is already sorted by an index matching the partition and order keys, the engine streams rows through the WindowAgg operator in O(N) time with minimal memory. Otherwise, it must sort the entire dataset in work_mem.
Q5.What happens if you omit PARTITION BY in a window function?
If PARTITION BY is omitted (e.g. OVER (ORDER BY salary DESC)), the entire table is treated as a single partition. The window function calculates rankings or running totals across all rows in the relation.
10. Interview-Ready Answer
“Window functions calculate analytics across partitions of rows using the OVER() clause without collapsing row identities. ROW_NUMBER assigns distinct sequences, RANK leaves gaps on ties, and DENSE_RANK numbers ties without gaps.”
11. Quick Test
Three employees tie for 1st place with identical salaries. What rank number will the fourth employee receive using RANK()?