We’re improving Formula Genius. We’re redesigning the app and fixing issues along the way. Sorry for any disruption, and thank you for your patience.
SQL advanced

SQL Window Functions: The Complete Guide

Window functions let you calculate across rows without grouping. Rankings, running totals, and row comparisons — all in one query.

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

The formula

Prompt

"Rank employees by salary within each department"

SQL
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

  1. RANK() — the window function that assigns rankings
  2. OVER (...) — defines the window (which rows to consider)
  3. PARTITION BY department — restart ranking for each department
  4. ORDER BY salary DESC — rank from highest to lowest salary
  5. 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

Prompt

"Engineering: salaries 120K, 110K, 110K, 100K"

SQL
Ranks: 1, 2, 2, 4 (RANK) or 1, 2, 2, 3 (DENSE_RANK)
Prompt

"Without PARTITION BY"

SQL
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 a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.