Window Functions · Lesson 58 of 64

SQL PARTITION BY

What you will learn

  • How PARTITION BY splits the rows into windows
  • How to show a group total or average beside each row
  • How to compute a share of the group
  • Why it replaces a correlated subquery

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. One window per group

OVER (PARTITION BY column) splits the rows into groups, like GROUP BY, but keeps every row. The function is calculated inside each group:

SELECT name, category_id, price,
       ROUND(AVG(price) OVER (PARTITION BY category_id), 2) AS category_avg
FROM products
ORDER BY category_id, product_id
LIMIT 6;
name              category_id  price  category_avg
----------------  -----------  -----  ------------
Steel pan                   2    6.6          31.5
Ceramic mug                 2   44.1          31.5
Wooden spoon set            2   29.5          31.5
Glass jar                   2    5.4          31.5
Chopping board              2   26.4          31.5
Tea kettle                  2   79.0          31.5
(6 rows)
SELECT account_id, branch_id, balance_cents,
       CAST(AVG(balance_cents) OVER (PARTITION BY branch_id) AS INTEGER) AS branch_avg
FROM accounts
ORDER BY branch_id, account_id
LIMIT 6;
account_id  branch_id  balance_cents  branch_avg
----------  ---------  -------------  ----------
         1          1         192400      130962
         4          1          99900      130962
        12          1         129800      130962
        18          1          76376      130962
        21          1          97600      130962
        28          1         230178      130962
(6 rows)
SELECT code, department_id, credits,
       ROUND(AVG(credits) OVER (PARTITION BY department_id), 2) AS department_avg
FROM courses
ORDER BY department_id, course_id
LIMIT 6;
code     department_id  credits  department_avg
-------  -------------  -------  --------------
MATH101              1        4            3.67
MATH201              1        3            3.67
MATH301              1        4            3.67
SCI101               2        4            3.75
SCI201               2        4            3.75
SCI202               2        4            3.75
(6 rows)

Rows of the same category show the same average; another category has its own. This is the correlated subquery of lesson 7.3, written in one line.

2. Difference from the group average

SELECT name, category_id, price,
       ROUND(price - AVG(price) OVER (PARTITION BY category_id), 2) AS vs_category
FROM products
ORDER BY vs_category DESC, product_id
LIMIT 5;
name          category_id  price  vs_category
------------  -----------  -----  -----------
Water bottle            8   86.9        51.73
Highlighters            5   79.0        50.99
Foam roller             9   79.0        49.72
Tea kettle              2   79.0         47.5
Drawing kit            10   53.9        30.69
(5 rows)
SELECT account_id, branch_id, balance_cents,
       balance_cents - CAST(AVG(balance_cents) OVER (PARTITION BY branch_id) AS INTEGER) AS vs_branch
FROM accounts
ORDER BY vs_branch DESC, account_id
LIMIT 5;
account_id  branch_id  balance_cents  vs_branch
----------  ---------  -------------  ---------
       398          4         502080     343139
       243          1         432800     301838
       165          1         428004     297042
       238          3         401600     280117
       127          3         361100     239617
(5 rows)
SELECT code, department_id, credits,
       ROUND(credits - AVG(credits) OVER (PARTITION BY department_id), 2) AS vs_department
FROM courses
ORDER BY vs_department DESC, code
LIMIT 5;
code     department_id  credits  vs_department
-------  -------------  -------  -------------
CS201                6        4           0.33
CS301                6        4           0.33
HUM101               4        3           0.33
HUM201               4        3           0.33
LANG101              3        3           0.33
(5 rows)

A positive number means the row is above its own group's average; negative, below.

3. Share of the group

SELECT name, category_id, stock,
       SUM(stock) OVER (PARTITION BY category_id) AS category_stock,
       ROUND(100.0 * stock / SUM(stock) OVER (PARTITION BY category_id), 1) AS percent_of_category
FROM products
WHERE category_id = 2
ORDER BY stock DESC, product_id
LIMIT 4;
name            category_id  stock  category_stock  percent_of_category
--------------  -----------  -----  --------------  -------------------
Ceramic mug               2    150             320                 46.9
Chopping board            2     80             320                 25.0
Glass jar                 2     40             320                 12.5
Tea kettle                2     25             320                  7.8
(4 rows)
SELECT account_id, branch_id, balance_cents,
       SUM(balance_cents) OVER (PARTITION BY branch_id) AS branch_total,
       ROUND(100.0 * balance_cents / SUM(balance_cents) OVER (PARTITION BY branch_id), 2) AS percent_of_branch
FROM accounts
WHERE branch_id = 1
ORDER BY balance_cents DESC, account_id
LIMIT 4;
account_id  branch_id  balance_cents  branch_total  percent_of_branch
----------  ---------  -------------  ------------  -----------------
       243          1         432800      11393760                3.8
       165          1         428004      11393760               3.76
       418          1         337200      11393760               2.96
       425          1         325400      11393760               2.86
(4 rows)
SELECT section_id, term, capacity,
       SUM(capacity) OVER (PARTITION BY term) AS term_seats,
       ROUND(100.0 * capacity / SUM(capacity) OVER (PARTITION BY term), 1) AS percent_of_term
FROM sections
WHERE term = '2025-Spring'
ORDER BY capacity DESC, section_id
LIMIT 4;
section_id  term         capacity  term_seats  percent_of_term
----------  -----------  --------  ----------  ---------------
        12  2025-Spring        35         480              7.3
        20  2025-Spring        35         480              7.3
        35  2025-Spring        35         480              7.3
        38  2025-Spring        35         480              7.3
(4 rows)

Remember that WHERE runs first: with WHERE category_id = 1 the group is already limited to that category.

4. Several partition columns

Partition by more than one column for finer groups:

SELECT status, ship_city, COUNT(*) AS orders_in_pair,
       SUM(COUNT(*)) OVER (PARTITION BY status) AS orders_with_status
FROM orders
GROUP BY status, ship_city
ORDER BY status, ship_city
LIMIT 5;
status     ship_city  orders_in_pair  orders_with_status
---------  ---------  --------------  ------------------
cancelled  Accra                   7                 170
cancelled  Austin                  7                 170
cancelled  Cairo                  15                 170
cancelled  Dhaka                   7                 170
cancelled  Hanoi                  15                 170
(5 rows)
SELECT account_type, status, COUNT(*) AS accounts_in_pair,
       SUM(COUNT(*)) OVER (PARTITION BY account_type) AS accounts_of_type
FROM accounts
GROUP BY account_type, status
ORDER BY account_type, status;
account_type  status  accounts_in_pair  accounts_of_type
------------  ------  ----------------  ----------------
checking      closed                21               316
checking      frozen                11               316
checking      open                 284               316
savings       closed                 9               134
savings       frozen                 5               134
savings       open                 120               134
(6 rows)
SELECT term, course_id, COUNT(*) AS sections_in_pair,
       SUM(COUNT(*)) OVER (PARTITION BY term) AS sections_in_term
FROM sections
GROUP BY term, course_id
ORDER BY term, course_id
LIMIT 5;
term         course_id  sections_in_pair  sections_in_term
-----------  ---------  ----------------  ----------------
2025-Autumn          1                 1                14
2025-Autumn          2                 1                14
2025-Autumn          3                 1                14
2025-Autumn          5                 1                14
2025-Autumn          6                 1                14
(5 rows)

This last example also shows that a window function can work on top of a GROUP BY: the window sees the grouped rows, so SUM(COUNT(*)) OVER (...) adds up the group counts.

5. PARTITION BY or GROUP BY plus join

Both can give a group value beside each row. The window form is shorter and cannot repeat rows by mistake; the join form can reuse a summary in many places. For a one-off report, prefer the window.

Worked example: who is above their group?

Step Do
1 choose the group: PARTITION BY category_id
2 put the group average beside each row: AVG(price) OVER (PARTITION BY category_id)
3 wrap in a CTE and keep rows where price > category_avg

The same answer as lesson 7.3, but with no subquery that runs once per row. The columns are from the Shop sample.

Common mistakes

  • Mixing up PARTITION BY and GROUP BY: the first keeps all rows.
  • Forgetting that WHERE shrinks the partition before the window is calculated.
  • Expecting the partition to order the rows.
  • Integer division in a percentage.

Key takeaways

  • OVER (PARTITION BY col) computes the function inside each group and keeps every row.
  • It gives group totals, averages and shares beside each row.
  • WHERE runs first and so changes the groups; a window can also sit on top of GROUP BY.
  • It replaces many correlated subqueries.

Practice

1. What does AVG(price) OVER (PARTITION BY category_id) return for two rows of the same category?

Show answer

The same value: the average price of that category.

2. How do you compute each product's share of its category's stock?

Show answer

100.0 * stock / SUM(stock) OVER (PARTITION BY category_id)

3. Does PARTITION BY reduce the number of rows?

Show answer

No. All rows are kept.

4. Which clause runs first, WHERE or the window?

Show answer

WHERE; the window is calculated on the rows that pass it.

5. What does SUM(COUNT(*)) OVER (PARTITION BY status) do after a GROUP BY?

Show answer

It adds up the group counts within each status.

6. Which old tool does a partitioned window often replace?

Show answer

A correlated subquery that computes a group value per row.