🎓 A1Learner
🔍
0 of 51 lessons completed

SQL Partition By

PARTITION BY restarts a window function in each group of rows. Each group gets its own numbering, its own totals, and its own averages.

Numbering inside each category

Five products carry the number 1, one at the head of each category.

SELECT name, category, price, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS row_num
FROM products
ORDER BY category, price DESC;

A total per category

Both Electronics rows carry 69.98, the total for their own group. Kitchen rows share 21.0, and Stationery rows share 5.3.

SELECT name, category, price, SUM(price) OVER (PARTITION BY category) AS category_total
FROM products
ORDER BY category, price DESC;

Dearest per category

Five rows come back, one per category: the dearest product in each.

SELECT name, category, price
FROM (SELECT name, category, price, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS row_num FROM products)
WHERE row_num = 1
ORDER BY category;

Example

SELECT name, category, price, AVG(price) OVER (PARTITION BY category) AS category_avg
FROM products
ORDER BY category, price DESC;

Key points

  • PARTITION BY: the clause inside OVER that splits rows into groups
  • A partition is one group of rows inside the window.
  • The window function starts again at the start of each partition.
  • Rows in different partitions never share a number or a total.
  • PARTITION BY keeps every row, unlike GROUP BY, which folds rows away.

In this example, AVG works inside each category partition, so every product carries the average price of its own category. The two Electronics products share 34.99, and the two Kitchen products share 10.5. Bags has one product, so its average is its own price, 39.99.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DB Fiddle

Exercise

What does PARTITION BY do inside OVER?