SQL Window Functions
Aggregate functions with GROUP BY collapse many rows into one. Window functions compute across a set of related rows too — but every row stays in the result, with the computed value added next to it. That makes rankings, running totals, moving averages and "compare with the previous row" queries easy.
function(...) OVER (
PARTITION BY columns -- optional: split rows into groups
ORDER BY columns -- optional: order within each group
frame -- optional: which rows around the current one
)Aggregates as window functions
Each product with its category's average price next to it:
SELECT name, category_id, price,
ROUND(AVG(price) OVER (PARTITION BY category_id), 2) AS category_avg,
COUNT(*) OVER (PARTITION BY category_id) AS in_category
FROM products
WHERE category_id IN (3, 7)
ORDER BY category_id, price;name | category_id | price | category_avg | in_category
---------------+-------------+-------+--------------+------------
Whole Milk | 3 | 1.45 | 4.4 | 3
Greek Yogurt | 3 | 3.95 | 4.4 | 3
Swiss Cheese | 3 | 7.8 | 4.4 | 3
Cast Iron Pan | 7 | 38 | 47.63 | 3
Chef Knife | 7 | 45 | 47.63 | 3
Coffee Grinder | 7 | 59.9 | 47.63 | 3
(6 rows)
With GROUP BY we would get one row per category; with OVER we keep all six products.
Ranking
| Function | Ties | Example values |
|---|---|---|
ROW_NUMBER() |
always unique | 1, 2, 3, 4 |
RANK() |
same rank, then a gap | 1, 2, 2, 4 |
DENSE_RANK() |
same rank, no gap | 1, 2, 2, 3 |
NTILE(n) |
splits rows into n buckets | 1, 1, 2, 2 |
SELECT first_name, title, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num,
RANK() OVER (PARTITION BY title ORDER BY salary DESC) AS rank_in_title
FROM employees
ORDER BY salary DESC;first_name | title | salary | row_num | rank_in_title
-----------+--------------------+--------+---------+--------------
Grace | CEO | 185000 | 1 | 1
Victor | Sales Manager | 98000 | 2 | 1
Lin | Operations Manager | 95000 | 3 | 1
Elena | Data Analyst | 72000 | 4 | 1
Rosa | Sales Rep | 62000 | 5 | 1
Aisha | Sales Rep | 60500 | 6 | 2
Tom | Sales Rep | 58000 | 7 | 3
Owen | Sales Rep | 55000 | 8 | 4
Marco | Warehouse Lead | 54000 | 9 | 1
Hana | Support Specialist | 51000 | 10 | 1
(10 rows)
Top N per group
A classic: the two best-selling products (by units) in each category. Rank inside a CTE, then filter — window functions cannot be used directly in WHERE:
WITH sales AS (
SELECT p.category_id, p.name, SUM(oi.quantity) AS units
FROM order_items AS oi
JOIN products AS p ON p.product_id = oi.product_id
GROUP BY p.product_id
),
ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY units DESC, name) AS rn
FROM sales
)
SELECT category_id, name, units
FROM ranked
WHERE rn <= 2 AND category_id <= 4
ORDER BY category_id, rn;category_id | name | units
------------+-----------------+------
1 | Sparkling Water | 21
1 | Chai Latte Mix | 12
2 | Bagels | 11
2 | Chocolate Cake | 10
3 | Greek Yogurt | 12
3 | Whole Milk | 10
4 | Cherry Tomatoes | 18
4 | Bananas | 16
(8 rows)
Running totals
With ORDER BY inside OVER, SUM becomes cumulative — the total of all rows up to the current one. Monthly revenue (without cancelled orders) with a running total and a three-month moving average:
WITH monthly AS (
SELECT substr(o.order_date, 1, 7) AS month,
ROUND(SUM(oi.quantity * p.price), 2) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
JOIN products AS p ON p.product_id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY month
)
SELECT month, revenue,
ROUND(SUM(revenue) OVER (ORDER BY month), 2) AS running_total,
ROUND(AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS moving_avg_3
FROM monthly
ORDER BY month;month | revenue | running_total | moving_avg_3
--------+---------+---------------+-------------
2025-01 | 216.74 | 216.74 | 216.74
2025-02 | 283.71 | 500.45 | 250.22
2025-03 | 340.77 | 841.22 | 280.41
2025-04 | 927.2 | 1768.42 | 517.23
2025-05 | 398.66 | 2167.08 | 555.54
2025-06 | 285.2 | 2452.28 | 537.02
2025-07 | 411.23 | 2863.51 | 365.03
2025-08 | 867.74 | 3731.25 | 521.39
2025-09 | 300.76 | 4032.01 | 526.58
2025-10 | 200.7 | 4232.71 | 456.4
(10 rows)
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is a frame: the average looks at the current month and the two before it.
LAG and LEAD: neighbouring rows
LAG(col) reads a value from the previous row, LEAD(col) from the next one. Days between consecutive orders of a customer:
SELECT customer_id, order_id, order_date,
LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS previous_order,
julianday(order_date)
- julianday(LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date)) AS days_since
FROM orders
WHERE customer_id IN (17, 22)
ORDER BY customer_id, order_date;customer_id | order_id | order_date | previous_order | days_since
------------+----------+------------+----------------+-----------
17 | 3 | 2025-01-19 | NULL | NULL
17 | 6 | 2025-02-10 | 2025-01-19 | 22
17 | 10 | 2025-03-13 | 2025-02-10 | 31
17 | 20 | 2025-05-15 | 2025-03-13 | 63
17 | 30 | 2025-08-10 | 2025-05-15 | 87
22 | 18 | 2025-05-11 | NULL | NULL
22 | 22 | 2025-06-06 | 2025-05-11 | 26
22 | 36 | 2025-09-10 | 2025-06-06 | 96
22 | 38 | 2025-10-09 | 2025-09-10 | 29
(9 rows)
Other useful window functions
| Function | Returns |
|---|---|
FIRST_VALUE(col) / LAST_VALUE(col) |
first/last value in the frame |
NTH_VALUE(col, n) |
n-th value in the frame |
PERCENT_RANK(), CUME_DIST() |
relative position (0–1) |
Named windows
If several functions share a window, name it once with WINDOW:
SELECT name, price,
MIN(price) OVER w AS cheapest,
MAX(price) OVER w AS dearest,
ROUND(price - AVG(price) OVER w, 2) AS diff_from_avg
FROM products
WHERE category_id = 1
WINDOW w AS (PARTITION BY category_id)
ORDER BY price;name | price | cheapest | dearest | diff_from_avg
----------------+-------+----------+---------+--------------
Orange Juice | 3.2 | 3.2 | 24.5 | -7.21
Sparkling Water | 4.6 | 3.2 | 24.5 | -5.81
Green Tea | 8.75 | 3.2 | 24.5 | -1.66
Chai Latte Mix | 11 | 3.2 | 24.5 | 0.59
Espresso Beans | 24.5 | 3.2 | 24.5 | 14.09
(5 rows)
Window functions are supported by SQLite 3.25+, PostgreSQL, MySQL 8+, SQL Server and Oracle.
Test yourself
What is the main difference between GROUP BY and a window function?
- Window functions are faster
- Window functions keep every row and add the computed value
- GROUP BY cannot use SUM
- There is none
With salaries 100, 90, 90, 80, what does RANK() give the last row (ordered DESC)?
- 3
- 4
- 2
- 1
Which function returns the value from the previous row?
- LEAD
- PREV
- LAG
- FIRST_VALUE