SQL: PARTITION BY
17 August 2023 (Updated 27 April 2025)
In a nutshell
The PARTITION BY clause lets you divide the result set of a query into partitions based on one or more columns, and then perform calculations against each partition using window functions like SUM(), MAX(), AVG().
Here’s an example use of PARTITION BY to find out how much each product category has sold to date.
SELECT
Product,
Category,
SaleDate,
SaleAmount,
SUM(SaleAmount) OVER (PARTITION BY Category ORDER BY SaleDate) AS RunningTotal
FROM
Sales;
This is what happens as the query is processed.
- Partitioning. The
PARTITION BY Categoryclause divides the result set into separate partitions where each partition contains only those rows inSaleswhere theCategorycolumn is the same. So you might have one partition for rows where theCategorycolumn is"Electrical", another partition where theCategorycolumn is “Gardening”, and so on. - Ordering. The
ORDER BY SaleDateorders the partition rows. - Window Function Calculation. After partitioning and ordering, the window function (something like
SUM()orAVG() is applied to each row within the partition. The result of the window function will only use the rows within the partition
Tagged:
SQL
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment