Thuta Learning
SQL
AdvancedData & DatabasesBeginner

Window Functions

SQLLesson 2935 min

What you'll walk away with

  • Explain how OVER (PARTITION BY ... ORDER BY ...) differs from GROUP BY
  • Choose between ROW_NUMBER, RANK and DENSE_RANK when values tie
  • Build running totals and day-to-day changes with SUM() OVER and LAG()
  • Filter on a window result through a CTE, because WHERE cannot see it

Explain it simply

Explain it simply

Picture a school exam results sheet. Every student keeps their own row, and you want to add one more column: "position in class". GROUP BY would squash the whole class into a single line that says "average 72", and the student names disappear.

A window function is like a calculator that stands on one row and looks through a window at the neighbouring rows before writing its answer. The number of rows stays the same; you simply gain a new column.

Problem → Why → Solution

The problem: keep the rows and still see the group

A manager asks for a report: every employee's name, their salary, and how far below the top salary in their department they are. "Top salary per department" sounds like GROUP BY, so you write the query below.

PostgreSQL refuses immediately: column "employees.employee" must appear in the GROUP BY clause or be used in an aggregate function. Once a department is collapsed into one row, the database cannot know which of four employee names to show. You can work around it with a self-join or a correlated subquery, but the query grows long and hard to read.

salary-report.sql
-- Goal: every employee + the gap to their department's top salary
SELECT department, employee, salary,
       MAX(salary) - salary AS gap_to_top
FROM employees
GROUP BY department;
-- ERROR: column "employees.employee" must appear in the GROUP BY clause
--        or be used in an aggregate function

Why GROUP BY cannot do this

GROUP BY changes the grain of the result, meaning what one row stands for: "one row per employee" becomes "one row per department". This report needs the employee grain kept intact while a group-level value is placed next to every row. That is exactly the job window functions were designed for.

Core concept: the OVER clause describes the window

A window function is an ordinary function call followed by OVER (...). What you write inside OVER is the window: which rows count as related to the current row. Besides window-only functions such as RANK(), ROW_NUMBER() and LAG(), you can put OVER after aggregates like SUM(), AVG() and MAX(). As soon as OVER is attached, the aggregate stops collapsing rows and returns one value per row instead.

1. PARTITION BY splits rows into groups

PARTITION BY department puts the Engineering rows and the Sales rows into two separate windows, and ranks restart at 1 in each one. Leave PARTITION BY out and the entire result is a single partition.

2. ORDER BY inside OVER orders each partition

Ranking functions, LAG/LEAD and running totals need to know which row comes first. This ORDER BY is only for the calculation; it does not control the display order. The order in which rows are shown is set separately by the query's final ORDER BY.

3. The frame decides how far to look

For an aggregate such as SUM() with ORDER BY inside OVER, the default frame runs from the start of the partition to the current row, including every peer row with the same sort value (RANGE mode). That produces a running total, but tied rows share one total. Without ORDER BY, the frame is the whole partition.

4. Windows are computed after WHERE

PostgreSQL evaluates window functions after FROM, WHERE, GROUP BY and HAVING, and before the final ORDER BY and LIMIT. That is why WHERE cannot use a window result: compute it inside a CTE or subquery first, then filter in the outer query.

FunctionTwo people tied at 4800
ROW_NUMBER()2, 3 - always unique; without a tiebreaker the order of tied rows is arbitrary
RANK()2, 2, then the next person is 4 - leaves a gap
DENSE_RANK()2, 2, then the next person is 3 - no gap
Mental model: stand on a row, look through a window
  1. Keep every row
  2. Split rows into partitions
  3. Order rows inside each partition
  4. Compute a value from the window
  5. Attach it as a new column

If the row count shrinks, you used GROUP BY, not a window function.

General pattern

sql
SELECT column_a, column_b,
       function_name(arguments) OVER (
         PARTITION BY group_column
         ORDER BY sort_column [ASC | DESC]
         [ROWS BETWEEN frame_start AND frame_end]
       ) AS new_column
FROM table_name
ORDER BY display_column;

All three parts inside OVER are optional: PARTITION BY groups, ORDER BY orders within the group, and the frame clause limits how many rows are visible. The ORDER BY at the end of the query is separate and only controls display order.

Salary ranking per department

Seven employees work in two departments, and in Engineering Min Thu and Zaw Lin tie at 4800. That tie lets you see the three ranking functions side by side. The last column uses MAX() as a window function and answers the manager's report from the problem section.

window-ranking.sql
SELECT department, employee, salary,
       RANK() OVER (
         PARTITION BY department
         ORDER BY salary DESC
       ) AS salary_rank,
       DENSE_RANK() OVER (
         PARTITION BY department
         ORDER BY salary DESC
       ) AS dense_rank,
       ROW_NUMBER() OVER (
         PARTITION BY department
         ORDER BY salary DESC, employee
       ) AS row_num,
       MAX(salary) OVER (PARTITION BY department) - salary AS gap_to_top
FROM employees
ORDER BY department, salary DESC, employee;

Code breakdown

  1. Partition per departmentPARTITION BY department

    Engineering and Sales are ranked separately, so Thida is number 1 in Sales and is never compared with Engineering salaries.

  2. RANK leaves a gapRANK() OVER (

    Both people at 4800 get 2, and Hnin Si becomes 4 because three people are ahead of her. DENSE_RANK gives her 3 instead.

  3. Tiebreaker for ROW_NUMBERORDER BY salary DESC, employee

    ROW_NUMBER must hand out distinct numbers even for ties, so the employee name is added as a second sort key. Only then is "Min Thu 2, Zaw Lin 3" the same on every run.

  4. Aggregate used as a windowMAX(salary) OVER (PARTITION BY department) - salary AS gap_to_top

    With no ORDER BY inside OVER, the frame is the whole department, so MAX returns that department's top salary on every row, and the row's own salary is subtracted from it.

  5. Display orderORDER BY department, salary DESC, employee;

    The ORDER BY clauses inside the windows do not guarantee the output order. This final ORDER BY is what makes the result display in a stable order.

You should see
 department  | employee  | salary | salary_rank | dense_rank | row_num | gap_to_top
-------------+-----------+--------+-------------+------------+---------+------------
 Engineering | Aye Chan  |   5200 |           1 |          1 |       1 |          0
 Engineering | Min Thu   |   4800 |           2 |          2 |       2 |        400
 Engineering | Zaw Lin   |   4800 |           2 |          2 |       3 |        400
 Engineering | Hnin Si   |   4100 |           4 |          3 |       4 |       1100
 Sales       | Thida     |   4300 |           1 |          1 |       1 |          0
 Sales       | Kyaw Kyaw |   3900 |           2 |          2 |       2 |        400
 Sales       | Nandar    |   3600 |           3 |          3 |       3 |        700
(7 rows)

Running totals, LAG and the frame trap

After ranking, the most common uses are running totals and comparisons with the previous row. SUM(amount) OVER (ORDER BY sale_day) shows the total up to each day, and LAG(amount) fetches the previous day's amount. The first day has no previous row, so LAG returns NULL and the change is NULL too.

running-total.sql
SELECT sale_day, amount,
       SUM(amount) OVER (ORDER BY sale_day) AS running_total,
       amount - LAG(amount) OVER (ORDER BY sale_day) AS change
FROM daily_sales
ORDER BY sale_day;
--   sale_day  | amount | running_total | change
--  2026-03-01 | 120.00 |        120.00 |
--  2026-03-02 |  80.00 |        200.00 | -40.00
--  2026-03-03 | 150.00 |        350.00 |  70.00
--  2026-03-04 |  60.00 |        410.00 | -90.00

sale_day is a primary key, so there are no ties. When the sort key does tie, the default RANGE frame adds all peer rows at once. In the query below, Min Thu and Zaw Lin both get a range_sum of 14800, while rows_sum, which uses a ROWS frame and a unique sort key, grows one row at a time.

frame-trap.sql
SELECT employee, salary,
       SUM(salary) OVER (ORDER BY salary DESC) AS range_sum,
       SUM(salary) OVER (
         ORDER BY salary DESC, employee
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS rows_sum
FROM employees
WHERE department = 'Engineering'
ORDER BY salary DESC, employee;
--  Aye Chan | 5200 |  5200 |  5200
--  Min Thu  | 4800 | 14800 | 10000
--  Zaw Lin  | 4800 | 14800 | 14800
--  Hnin Si  | 4100 | 18900 | 18900

In other databases

ROW_NUMBER, RANK, LAG and the OVER syntax are standard SQL, so they look almost the same in PostgreSQL, SQL Server, Oracle, MySQL 8.0 and later, and SQLite 3.25 and later. Some systems such as Snowflake, BigQuery and DuckDB offer a QUALIFY clause that filters on window results directly; PostgreSQL does not have it, so you use a CTE.

In real projects

In real projects

The most common pattern is "the latest row of each group". To get every customer's most recent order, compute ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) and keep the rows numbered 1. PostgreSQL also has a shorter DISTINCT ON (customer_id), but that is PostgreSQL-only, while the ROW_NUMBER pattern works on most databases.

A running balance next to every bank transaction, a dashboard tile saying "+12% versus last month" (LAG), a game leaderboard (DENSE_RANK), and finding duplicate rows with ROW_NUMBER before a data migration are all written with window functions. Computing these in the database, instead of looping in application code, also avoids shipping thousands of rows over the network.

Common mistakes

Common mistakes

Filtering a window result in WHERE

Writing WHERE RANK() OVER (...) <= 2 fails with "window functions are not allowed in WHERE", and WHERE salary_rank <= 2 says the column does not exist. WHERE runs before windows are computed. Calculate the rank inside a CTE and filter in the outer SELECT.

Using ROW_NUMBER without a tiebreaker

With ORDER BY salary DESC alone, PostgreSQL does not promise which of the two 4800 earners gets number 2. A data change or a different plan can silently swap who appears in a "top 2" report. Add a unique column such as id or name as the last sort key.

Running totals over ties with the default frame

When the sort key has duplicates, the default RANGE frame adds those rows together, so the same total repeats. For a total that grows row by row, use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW plus a unique sort key.

Expecting OVER's ORDER BY to sort the output

OVER (ORDER BY ...) only drives the calculation, and two windows can use different orders. State the output order explicitly with an ORDER BY at the end of the query.

Mini challenge

Top two earners per department

Using the lesson's employees table, write a query that shows only the two highest-paid people in each department. Even with ties, no department may show more than two people.

  • Number the rows per department with ROW_NUMBER() inside a CTE called ranked
  • Order by salary, highest first, and break ties by employee name
  • Filter with rn <= 2 in the outer query
  • Sort the result by department, then by rn
top-two.sql
WITH ranked AS (
  SELECT department, employee, salary
         -- TODO: add a ROW_NUMBER() column named rn:
         --       one sequence per department, highest salary first,
         --       ties broken by employee name
  FROM employees
)
SELECT department, employee, salary, rn
FROM ranked
-- TODO: keep only the first two rows of each department
-- TODO: order by department, then rn
;

Expected: Four rows: Engineering shows Aye Chan (5200, 1) and Min Thu (4800, 2); Sales shows Thida (4300, 1) and Kyaw Kyaw (3900, 2).

Show hint

With RANK() both 4800 earners would get 2 and Engineering could show three people. When you need exactly N rows, use ROW_NUMBER with a tiebreaker.

Show solution
top-two.sql
WITH ranked AS (
  SELECT department, employee, salary,
         ROW_NUMBER() OVER (
           PARTITION BY department
           ORDER BY salary DESC, employee
         ) AS rn
  FROM employees
)
SELECT department, employee, salary, rn
FROM ranked
WHERE rn <= 2
ORDER BY department, rn;

Quick quiz 1 / 3

Four rows have salaries 900, 800, 800 and 700. With DENSE_RANK() OVER (ORDER BY salary DESC), what does 700 get?

Quick quiz 2 / 3

What happens when PostgreSQL runs SELECT employee, RANK() OVER (ORDER BY salary DESC) AS r FROM employees WHERE r <= 3;?

Quick quiz 3 / 3

You need exactly one row per customer: their latest order. Every window already has PARTITION BY customer_id. Which function and ordering fit best?

What to remember

  • Window functions add a value to every row without collapsing rows
  • PARTITION BY groups rows; ORDER BY inside OVER sets the calculation order
  • ROW_NUMBER, RANK and DENSE_RANK differ on ties; use ROW_NUMBER plus a tiebreaker for exactly N rows
  • To filter on a window result, compute it in a CTE or subquery first
  • For running totals over ties, use a ROWS frame and a unique sort key

Window Functions Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.