Skip to content
Back to 50 Concepts
Topic 46 of 50query-executionAdvanced

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Window Functions Visual Simulator

Step 1 of 3
SQL>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 Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Window Functions
SQL Input

Initiating Window Functions

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Olympics Podium: If two runners tie for Gold, they both get Gold medals (1st), nobody gets Silver, and the next runner gets Bronze (3rd).

4. Real-World Example

Ranking employees by salary within each department while retaining all individual employee rows.

Window Ranking
NameDeptSalaryROW_NUMBER()RANK()DENSE_RANK()
AliceEng$120,000111
BobEng$120,000211
CharlieEng$90,000332
Relational walkthrough: Notice how RANK skips rank 2 due to the tie, whereas DENSE_RANK does not create a gap.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Department ranking with ROW_NUMBER
SELECT 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;
Rows are NOT collapsed; each employee receives their own row.

6. Important Rules & Behaviors

RuleBehavioral Explanation
No Row CollapsingUnlike GROUP BY, window functions retain the exact same number of rows as the input query.
WHERE Clause RestrictionWindow functions are evaluated in the SELECT projection step and CANNOT be placed in WHERE or HAVING.
Default Frame SpecificationAn 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 BYGROUP 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!)
Caution: To filter on window function results (e.g. WHERE rank = 1), you MUST wrap the query in a CTE or derived table.

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.

ScoreROW_NUMBER()RANK()DENSE_RANK()
100111
95222
95322
90443
85554

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

Scenario Question:

Three employees tie for 1st place with identical salaries. What rank number will the fourth employee receive using RANK()?

Select your answer: