SQL Window Functions: The Complete Guide
SQL Window Functions is a SQL query that rank() assigns a ranking number to each row within its department partition, ordered by salary descending. Formula Genius generates and validates this formula automatically from a plain-English prompt.
Window functions let you calculate across rows without grouping. Rankings, running totals, and row comparisons — all in one query.
The Formula
"Rank employees by salary within each department"
SELECT
department,
name,
salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees;
RANK() assigns a ranking number to each row within its department partition, ordered by salary descending. The highest salary gets rank 1.
Step-by-Step Breakdown
- RANK() — the window function that assigns rankings
- OVER (...) — defines the window (which rows to consider)
- PARTITION BY department — restart ranking for each department
- ORDER BY salary DESC — rank from highest to lowest salary
- Tied salaries get the same rank; next rank skips (1,1,3 not 1,1,2)
Edge Cases & Warnings
- RANK vs DENSE_RANK: RANK skips numbers after ties (1,1,3), DENSE_RANK doesn't (1,1,2)
- ROW_NUMBER always gives unique numbers even for ties (arbitrary tiebreaker)
- NULL salaries are typically ranked last (database-dependent)
- Window functions cannot be used in WHERE — use a subquery or CTE
Examples
"Engineering: salaries 120K, 110K, 110K, 100K"
Ranks: 1, 2, 2, 4 (RANK) or 1, 2, 2, 3 (DENSE_RANK)
"Without PARTITION BY"
Ranks across ALL departments combined
Frequently Asked Questions
When should I use window functions instead of GROUP BY?
Use window functions when you need to keep individual rows visible while also calculating aggregates. GROUP BY collapses rows; window functions don't.
Do all databases support window functions?
All modern databases do: PostgreSQL, MySQL 8+, SQL Server, Oracle, SQLite 3.25+. MySQL 5.7 and earlier don't support them.
Can't find what you need?
Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.