01 / 21

Windowed
Aggregates

Master OVER(PARTITION BY ...) to compute aggregates across groups of rows — without collapsing your result set.

SQL

What Is a Window Function?

A window function performs a calculation across a set of rows that are somehow related to the current row. Unlike a regular aggregate (GROUP BY), it does not collapse the rows into one — every original row stays in the output, each enriched with the computed value.

GROUP BY vs Window Functions

GROUP BY Alice | Sales | 5000 Bob | Sales | 7000 Carol | Eng | 6000 Dave | Eng | 8000 Sales | 12000 Eng | 14000 2 rows (collapsed) OVER(PARTITION BY ...) Alice | Sales | 5000 Bob | Sales | 7000 Carol | Eng | 6000 Dave | Eng | 8000 Alice | Sales | 5000 | 12000 Bob | Sales | 7000 | 12000 Carol | Eng | 6000 | 14000 Dave | Eng | 8000 | 14000 4 rows (all kept!)

Why Does This Matter?

Side-by-Side
Compare each row's value to its group total — no self-join needed.
Running Totals
Compute cumulative sums, averages, or counts over ordered rows.
Rankings
Rank, number, or percentile rows within each group effortlessly.

The Anatomy of OVER()

SELECT
  column,
  SUM(amount) OVER (
    PARTITION BY group_col
    ORDER BY     sort_col
    -- optional frame clause
  ) AS window_result
FROM table_name;
PARTITION BY
Splits rows into groups (like GROUP BY, but keeps all rows).
ORDER BY
Defines row order within each partition — essential for running totals.
Frame
Optionally limits which rows in the partition the function "sees".

PARTITION BY Deep Dive

PARTITION BY divides the result set into partitions — groups of rows that share the same value(s) in the specified column(s). The window function is computed independently for each partition.

Partition: Sales Alice | 5000 | 12000 Bob | 7000 | 12000
\(\text{SUM} = 5000 + 7000\)
\(= 12000\)
Partition: Eng Carol | 6000 | 14000 Dave | 8000 | 14000
\(\text{SUM} = 6000 + 8000\)
\(= 14000\)

GROUP BY vs PARTITION BY

GROUP BY PARTITION BY
Output rows One per group All original rows
Used in Own clause (after WHERE) SELECT (OVER clause)
Non-agg columns Must be in GROUP BY list Any column is fine
Ordering support Separate ORDER BY ORDER BY inside OVER
Running totals Requires subquery Built-in

How to Apply Window Aggregates

1
Choose the aggregate function: SUM, AVG, COUNT, MIN, MAX, or others.
2
Add OVER(...): This tells SQL it's a window function, not a regular aggregate.
3
Specify PARTITION BY: Which column(s) define the groups? Omit for "whole table".
4
Optional ORDER BY: Add this inside OVER to get running (cumulative) results.
5
Alias the result: Use AS to name your new computed column clearly.

Example 1: Department Totals

SELECT
  name,
  dept,
  salary,
  SUM(salary) OVER (
    PARTITION BY dept
  ) AS dept_total
FROM employees;
namedeptsalarydept_total
AliceSales500012000
BobSales700012000
CarolEng600014000
DaveEng800014000

Example 2: Percentage of Group

SELECT
  name,
  dept,
  salary,
  ROUND(
    100.0 * salary
    / SUM(salary) OVER (PARTITION BY dept),
    1
  ) AS pct_of_dept
FROM employees;
namedeptsalarypct_of_dept
AliceSales500041.7%
BobSales700058.3%
CarolEng600042.9%
DaveEng800057.1%

Example 3: Running Total

SELECT
  order_date,
  amount,
  SUM(amount) OVER (
    ORDER BY order_date
  ) AS running_total
FROM orders;
order_dateamountrunning_total
Jan 1100100
Jan 3250350
Jan 5150500
Jan 8300800

Combining PARTITION BY + ORDER BY

SELECT
  dept, name, salary,
  SUM(salary) OVER (
    PARTITION BY dept
    ORDER BY salary
  ) AS running_in_dept
FROM employees;
deptnamesalaryrunning_in_dept
EngCarol60006000
EngDave800014000
SalesAlice50005000
SalesBob700012000

Other Aggregate Functions in OVER

AVG()
Average salary per department — compare each employee to their group mean.
COUNT()
Number of employees in each department — without a separate query.
MAX() / MIN()
Find the highest or lowest value within each partition alongside every row.
SELECT name, dept, salary,
  AVG(salary)   OVER (PARTITION BY dept) AS avg_sal,
  COUNT(*)      OVER (PARTITION BY dept) AS dept_size,
  MAX(salary)   OVER (PARTITION BY dept) AS top_sal
FROM employees;

OVER() with No Partition

If you write OVER() with empty parentheses — no PARTITION BY, no ORDER BY — the window covers the entire result set. Every row gets the same grand total.

SELECT
  name, salary,
  SUM(salary) OVER () AS grand_total
FROM employees;
namesalarygrand_total
Alice500026000
Bob700026000
Carol600026000
Dave800026000

Common Mistakes

✕ Mixing GROUP BY + Window
Adding a window function in a query that already uses GROUP BY without understanding that the window runs after grouping. The partitions operate on the grouped result, not the original rows.
✕ Forgetting OVER()
Writing SUM(salary) without OVER causes a normal aggregate. SQL will complain that non-aggregated columns aren't in GROUP BY.
✕ Unintended Running Sum
Adding ORDER BY inside OVER when you wanted a full partition total. ORDER BY changes the default frame to "rows up to current" — making it cumulative.

Cheat Sheet: Window Aggregate Patterns

Pattern OVER Clause Result
Grand total \(\texttt{OVER}()\) Same value on every row
Group total \(\texttt{OVER}(\texttt{PARTITION BY col})\) Same value within each group
Running total \(\texttt{OVER}(\texttt{ORDER BY col})\) Cumulative across whole table
Running total per group \(\texttt{OVER}(\texttt{PARTITION BY g ORDER BY c})\) Cumulative, resets per group
Percentage of group \(\texttt{val} / \texttt{SUM}(\texttt{val}) \texttt{ OVER } (\texttt{PARTITION BY g})\) Each row's share

Question 1 of 5

What does PARTITION BY do inside an OVER clause?

Question 2 of 5

Given this query, what does dept_avg represent?

Question 3 of 5

What happens when you write SUM(amount) OVER (ORDER BY order_date) without PARTITION BY?

Question 4 of 5

A developer wants the total salary per department next to each row, but accidentally writes:

What is wrong with this query?

Question 5 of 5

How would you compute each employee's salary as a percentage of the grand total (across all departments)?