In SQL, the PARTITION BY clause is a fundamental component of window functions that enables you to divide a result set into logical segments, or partitions, before calculating aggregates, rankings, or other analytic metrics. But unlike the traditional GROUP BY, which collapses multiple rows into a single summary row, PARTITION BY preserves the individual detail rows while performing calculations within each partition. This capability makes it indispensable for generating running totals, year-over-year comparisons, top-N queries per category, and a wide range of reporting scenarios without losing granularity Less friction, more output..
Understanding the Basics of PARTITION BY
At its core, PARTITION BY operates similarly to GROUP BY in that it segments data. That said, the outcome is dramatically different. Which means when you use PARTITION BY, the database engine partitions the rows based on the specified column(s), but each partition still contains all its original rows. Window functions then operate on these partitions independently, returning a result for every row in the original dataset.
The basic syntax for a window function incorporating PARTITION BY looks like this:
SELECT column_name,
SUM(column_name) OVER (PARTITION BY partition_column ORDER BY order_column) AS running_total
FROM table_name;
Here, the OVER clause defines the window, and PARTITION BY determines how the data is split before the window function runs. If PARTITION BY is omitted, the entire result set is treated as a single partition, effectively behaving like a standard aggregate with an overlay of row-level detail Simple as that..
Some disagree here. Fair enough.
How PARTITION BY Differs from GROUP BY
A common point of confusion for beginners is the distinction between PARTITION BY and GROUP BY. While both segment data, their purposes and outputs differ:
- GROUP BY aggregates rows, meaning it reduces the number of rows in the result set. Each unique combination of grouping columns produces one output row, and any selected columns must either be part of the grouping set or used within an aggregate function.
- PARTITION BY does not reduce row count. It keeps every row intact and applies the window function across each partition. This allows you to compare values within a group while still seeing the full detail of each record.
Here's one way to look at it: if you want to see each employee's salary alongside the average salary of their department, PARTITION BY department_id lets you display every employee row with the department average
...repeated on every row for easy comparison. With GROUP BY, you would only get one row per department, losing the individual employee context entirely.
The Critical Role of ORDER BY Within the Window
While PARTITION BY defines the scope of the calculation (the "who"), the ORDER BY clause inside the OVER clause defines the sequence (the "when"). This distinction is vital because it fundamentally changes the behavior of certain window functions.
For ranking functions (ROW_NUMBER, RANK, DENSE_RANK), ORDER BY is mandatory—it determines the sort order used to assign ranks. For aggregate functions (SUM, AVG, COUNT, MIN, MAX), including ORDER BY transforms the calculation from a "partition-wide" aggregate into a running (cumulative) aggregate.
Consider the difference:
-- 1. Partition Aggregate (Static value per partition)
SUM(salary) OVER (PARTITION BY department_id) AS dept_total_salary
-- 2. Running Total (Dynamic value per row)
SUM(salary) OVER (PARTITION BY department_id ORDER BY hire_date) AS running_dept_payroll
In the first example, every row in the 'Sales' department shows the same total payroll. In the second, the value accumulates row-by-row based on hire_date, showing the payroll growth over time within that department.
Defining Window Frames: ROWS vs. RANGE
When ORDER BY is present, you can further restrict the window using a Frame Clause (ROWS BETWEEN ...). orRANGE BETWEEN ...This allows for calculations like moving averages or "year-to-date" figures that don't necessarily span the entire partition.
ROWS: Defines the frame based on physical row offsets (e.g., "the current row and the 2 preceding rows").RANGE: Defines the frame based on logical value offsets relative to theORDER BYexpression (e.g., "all rows where the order_date is within 30 days of the current row's order_date").
Syntax Example: 3-Month Moving Average
SELECT
sales_date,
amount,
AVG(amount) OVER (
PARTITION BY region_id
ORDER BY sales_date
RANGE BETWEEN INTERVAL '3' MONTH PRECEDING AND CURRENT ROW
) AS moving_avg_3mo
FROM sales_data;
Note: RANGE with intervals requires the ORDER BY column to be a numeric, date, or timestamp type. ROWS is generally more performant and predictable for "Top N" or fixed-window calculations.
Practical Patterns and Use Cases
1. Top-N Per Group (The "Greatest-N-Per-Group" Problem)
This is perhaps the most celebrated use case. Before window functions, this required complex self-joins or correlated subqueries. Now, it is elegant and readable It's one of those things that adds up..
WITH ranked_products AS (
SELECT
product_id,
category_id,
unit_price,
ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY unit_price DESC) as rn
FROM products
)
SELECT product_id, category_id, unit_price
FROM ranked_products
WHERE rn <= 3; -- Top 3 most expensive products per category
Use RANK() or DENSE_RANK() instead of ROW_NUMBER() if you need to handle ties (e.g., two products sharing the #1 price spot).
2. Gap and Island Analysis / Sessionization
Identifying contiguous sequences (islands) separated by gaps is a classic analytics problem. By partitioning by a user/entity and ordering by time, you can flag the start of a new "session" or "island."
SELECT
user_id,
event_time,
-- Flag 1 if gap > 30 mins, else 0
CASE
WHEN LAG(event_time) OVER (PARTITION BY user_id ORDER BY event_time)
< event_time - INTERVAL '30 MINUTES'
THEN 1 ELSE 0
END AS new_session_flag
FROM user_events;
A running SUM() over this flag then assigns a unique session_id to every contiguous block of activity The details matter here..
3. Data Deduplication
Keeping only the "latest" or "most complete" record per primary key is a standard ETL pattern Not complicated — just consistent..
DELETE FROM staging_table
WHERE ctid IN (
SELECT ctid FROM (
SELECT
ctid,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC, completeness_score DESC) as rn
FROM staging_table
) t
WHERE rn > 1
);
4. Running Totals and Percent of Total
Financial reporting relies heavily on these.
Running Totals & “Percent‑of‑Total” – A Quick Guide
Window functions let you turn a simple row into a cumulative measure while still preserving the original columns. Two of the most common patterns are:
| Goal | Window clause | Typical output |
|---|---|---|
| Cumulative sum / count (e.g., “total sales up to today”) | SUM(col) OVER (ORDER BY … ROWS UNBOUNDED PRECEDING) |
Running total |
| Current share of the whole (e.g., “sales as % of all sales ever recorded”) | Divide the running total by the grand total (`SUM(... |
1. Cumulative totals (running totals)
SELECT
sale_date,
amount,
SUM(amount) OVER (
ORDER BY sale_date
ROWS UNBOUNDED PRECEDING -- include the current row
) AS running_total
FROM sales_data;
The ROWS UNBOUNDED PRECEDING frame always starts at the first row of the partition and extends forward row‑by‑row.
If your data is naturally timestamped