28. Window functions

Work out over a group of rows, as GROUP BY does, yet keep every row: rankings, shares of a total, the best of each group.

GROUP BY folds rows; OVER keeps them

Chapter 10's GROUP BY folds the rows of each group into one. Ask for the average price of each category and you get 4 rows, one per category; the products themselves are gone:

SELECT category_id, count(*) AS products, avg(price) AS avg_price
FROM product
GROUP BY category_id;
category_idproductsavg_price
1346.6666666666667
2371.6666666666667
3388.3333333333333
4323.3333333333333
4 rows

Often you want both at once: each product, and a figure worked out over many rows beside it, such as "how far is this price from the average?". That is what a window function does. Put OVER (...) after a function like avg() and it no longer folds rows: it works over a "window" of rows and writes the answer on every row.

OVER () with nothing inside means the window is the whole result:

SELECT name, price, avg(price) OVER () AS avg_all, price - avg(price) OVER () AS diff
FROM product
ORDER BY id;
namepriceavg_alldiff
Coffee55.057.5-2.5
Green Tea45.057.5-12.5
Orange Juice40.057.5-17.5
Croissant35.057.5-22.5
Banana Bread60.057.52.5
Cheesecake120.057.562.5
Potato Chips25.057.5-32.5
Dried Mango90.057.532.5
Cashew Nuts150.057.592.5
Notebook30.057.5-27.5
Pen15.057.5-42.5
Highlighter25.057.5-32.5
12 rows

All 12 products are still there. Each has the average of all 12, 57.5, beside it, and diff shows how far it is from the average: Cashew Nuts is 92.5 above it, Pen 42.5 below.

Every aggregate you know, count, sum, avg, min, max, works as a window function once it has OVER.

PARTITION BY: a window for each group

PARTITION BY splits the rows into groups, as GROUP BY does, but again keeps every row. Each row sees only the rows of its own group:

SELECT name, category_id, price,
       count(*)   OVER (PARTITION BY category_id) AS in_category,
       avg(price) OVER (PARTITION BY category_id) AS category_avg
FROM product
ORDER BY category_id, id;
namecategory_idpricein_categorycategory_avg
Coffee155.0346.6666666666667
Green Tea145.0346.6666666666667
Orange Juice140.0346.6666666666667
Croissant235.0371.6666666666667
Banana Bread260.0371.6666666666667
Cheesecake2120.0371.6666666666667
Potato Chips325.0388.3333333333333
Dried Mango390.0388.3333333333333
Cashew Nuts3150.0388.3333333333333
Notebook430.0323.3333333333333
Pen415.0323.3333333333333
Highlighter425.0323.3333333333333
12 rows

Coffee, Green Tea and Orange Juice (category 1) each see the 3 drinks, with their average of about 46.67; Croissant, Banana Bread and Cheesecake see the bakery's average of about 71.67, and so on. These are the same numbers as the GROUP BY above, now written beside each product.

The ORDER BY at the end of the statement only sorts what comes out. It has nothing to do with the windows: a window decides which rows a function sees, not the order the result is shown in.

ORDER BY inside OVER: numbering and ranking

Put ORDER BY inside OVER and the rows of the window are lined up in that order. Now functions that number rows make sense. row_number() gives 1, 2, 3, ... in that order:

SELECT name, price, row_number() OVER (ORDER BY price DESC, name) AS place
FROM product
ORDER BY place;
namepriceplace
Cashew Nuts150.01
Cheesecake120.02
Dried Mango90.03
Banana Bread60.04
Coffee55.05
Green Tea45.06
Orange Juice40.07
Croissant35.08
Notebook30.09
Highlighter25.010
Potato Chips25.011
Pen15.012
12 rows

Cashew Nuts, the dearest, is 1; Pen, the cheapest, is 12.

Highlighter and Potato Chips cost the same, 25. If the ORDER BY inside OVER were only price DESC, which of them came first would be left to chance, and could change one day. That is why name is there too, to settle ties. When you number rows, always order by something that cannot tie (add id or name at the end).

When ties should share a place, as in a contest, there are three ways to number. See them side by side:

SELECT name, price,
       row_number() OVER (ORDER BY price, name) AS row_number,
       rank()       OVER (ORDER BY price) AS rank,
       dense_rank() OVER (ORDER BY price) AS dense_rank
FROM product
ORDER BY price, name;
namepricerow_numberrankdense_rank
Pen15.0111
Highlighter25.0222
Potato Chips25.0322
Notebook30.0443
Croissant35.0554
Orange Juice40.0665
Green Tea45.0776
Coffee55.0887
Banana Bread60.0998
Dried Mango90.010109
Cheesecake120.0111110
Cashew Nuts150.0121211
12 rows

ntile(n) shares the rows out into n groups as evenly as it can, in order. ntile(4) splits the products into quarters by price:

SELECT name, price, ntile(4) OVER (ORDER BY price, name) AS quarter
FROM product
ORDER BY price, name;
namepricequarter
Pen15.01
Highlighter25.01
Potato Chips25.01
Notebook30.02
Croissant35.02
Orange Juice40.02
Green Tea45.03
Coffee55.03
Banana Bread60.03
Dried Mango90.04
Cheesecake120.04
Cashew Nuts150.04
12 rows

12 products in 4 groups make 3 to a group: quarter 1 is the cheapest three, quarter 4 the dearest three.

PARTITION BY and ORDER BY can go together in the same OVER: numbering starts again at 1 in each group. Here is each product's place within its own category, by price:

SELECT category_id, name, price,
       row_number() OVER (PARTITION BY category_id ORDER BY price DESC) AS place_in_category
FROM product
ORDER BY category_id, place_in_category;
category_idnamepriceplace_in_category
1Coffee55.01
1Green Tea45.02
1Orange Juice40.03
2Cheesecake120.01
2Banana Bread60.02
2Croissant35.03
3Cashew Nuts150.01
3Dried Mango90.02
3Potato Chips25.03
4Notebook30.01
4Highlighter25.02
4Pen15.03
12 rows

Windows are worked out after WHERE and GROUP BY

A statement works in this order: FROM, then WHERE, then GROUP BY and HAVING, and only then the window functions in SELECT, and last ORDER BY. So WHERE cannot use a window function: when WHERE runs, the window has not been worked out yet:

SELECT name, price
FROM product
WHERE row_number() OVER (ORDER BY price DESC) <= 3;
Error: misuse of window function row_number()

The way out is a CTE (chapter 26): work out the numbers in one step, then pick rows from it in the next:

WITH numbered AS (
  SELECT name, price, row_number() OVER (ORDER BY price DESC, name) AS place
  FROM product
)
SELECT name, price, place FROM numbered
WHERE place <= 3
ORDER BY place;
namepriceplace
Cashew Nuts150.01
Cheesecake120.02
Dried Mango90.03
3 rows

Coming after GROUP BY has a good side, though: a window function can rank groups that GROUP BY has just made. Here each order's total is ranked from the biggest down:

SELECT o.id, o.ordered, sum(oi.qty * oi.price) AS total,
       rank() OVER (ORDER BY sum(oi.qty * oi.price) DESC) AS place
FROM orders AS o JOIN order_item AS oi ON oi.order_id = o.id
GROUP BY o.id
ORDER BY place, o.id;
idorderedtotalplace
92026-10-22490.01
82026-10-15390.02
152026-11-25375.03
42026-09-20300.04
112026-11-02300.04
62026-10-03290.06
72026-10-10235.07
12026-09-02180.08
32026-09-12175.09
122026-11-05175.09
22026-09-05165.011
52026-10-01150.012
132026-11-1190.013
142026-11-1880.014
102026-10-2845.015
15 rows

Order 9 is the biggest, 490 baht. Orders 4 and 11 both come to 300 and share 4th place, so the next is 6th; orders 3 and 12 share 9th at 175, and the next is 11th. rank() does exactly what a contest does.

The best seller of each category

"The best one of each group" (the top seller of each category, the latest order of each customer) is one of the commonest questions in real work, and window functions answer it neatly. First, how many of each product sold:

SELECT p.category_id, p.name, sum(oi.qty) AS sold
FROM product AS p JOIN order_item AS oi ON oi.product_id = p.id
GROUP BY p.id
ORDER BY p.category_id, sold DESC;
category_idnamesold
1Coffee7
1Green Tea5
1Orange Juice2
2Croissant6
2Banana Bread3
2Cheesecake3
3Potato Chips11
3Dried Mango4
3Cashew Nuts2
4Pen35
4Notebook18
11 rows

11 rows: Highlighter has never sold, so the JOIN leaves it out. Now three steps in a CTE: add up sales, rank them within each category, keep those ranked 1:

WITH sales AS (
  SELECT p.category_id, p.name, sum(oi.qty) AS sold
  FROM product AS p JOIN order_item AS oi ON oi.product_id = p.id
  GROUP BY p.id
),
ranked AS (
  SELECT category_id, name, sold,
         rank() OVER (PARTITION BY category_id ORDER BY sold DESC) AS place
  FROM sales
)
SELECT c.name AS category, r.name AS best_seller, r.sold
FROM ranked AS r JOIN category AS c ON c.id = r.category_id
WHERE r.place = 1
ORDER BY c.id;
categorybest_sellersold
DrinksCoffee7
BakeryCroissant6
SnacksPotato Chips11
StationeryPen35
4 rows

Coffee leads the drinks with 7, Croissant the bakery with 6, Potato Chips the snacks with 11, and Pen the stationery with 35.

Choose the numbering by what you want when there is a tie. rank() (or dense_rank()) with place = 1 gives every product that shares first place, so a category might show two rows. row_number() gives exactly one row per category, but which of the tied ones is left to your ORDER BY. For "the top 3 of each group" use place <= 3 the same way.

  1. Give every customer a member number, 1, 2, 3, ... in the order they joined (joined).
  2. Show each order's total and its place among all orders, the biggest first, with tied orders sharing a place.
  3. Show the two cheapest products of each category (if prices tie, the name decides).
Show the answer
SELECT name, joined, row_number() OVER (ORDER BY joined, id) AS member_no
FROM customer
ORDER BY member_no;

SELECT o.id, sum(oi.qty * oi.price) AS total,
       rank() OVER (ORDER BY sum(oi.qty * oi.price) DESC) AS place
FROM orders AS o JOIN order_item AS oi ON oi.order_id = o.id
GROUP BY o.id
ORDER BY place, o.id;

WITH ranked AS (
  SELECT category_id, name, price,
         row_number() OVER (PARTITION BY category_id ORDER BY price, name) AS place
  FROM product
)
SELECT category_id, name, price FROM ranked
WHERE place <= 2
ORDER BY category_id, place;
namejoinedmember_no
Somchai Jaidee2025-01-151
Malee Srisuk2025-03-022
Anan Wongsa2025-04-203
Pim Chaiya2025-06-114
Narin Thongdee2025-08-305
Kanya Boonmee2025-10-056
Wichai Saelim2026-01-097
Siriporn Kaewdee2026-02-148
Tawan Rungruang2026-05-219
Lalita Meesuk2026-08-0310
10 rows
idtotalplace
9490.01
8390.02
15375.03
4300.04
11300.04
6290.06
7235.07
1180.08
3175.09
12175.09
2165.011
5150.012
1390.013
1480.014
1045.015
15 rows
category_idnameprice
1Orange Juice40.0
1Green Tea45.0
2Croissant35.0
2Banana Bread60.0
3Potato Chips25.0
3Dried Mango90.0
4Pen15.0
4Highlighter25.0
8 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made