Aggregate Window Functions (SUM() OVER, AVG() OVER, COUNT() OVER)
Apply SUM/AVG/COUNT as windows to annotate every detail row.
In plain words
Add OVER to SUM or AVG and every row gets its group's total or average, while all the rows stay.
Think of it like…
A shopping receipt that prints, next to every item, the total for its department and the bill total, so you can see each item's share without adding anything up yourself.
Where you’ve seen it
Each order's share of its customer's lifetime spend: SELECT id, customer_id, amount, amount / SUM(amount) OVER (PARTITION BY customer_id) AS share_of_customer, COUNT(*) OVER (PARTITION BY customer_id) AS orders_for_customer FROM orders;
Words you’ll hear
- Window aggregate
- An aggregate with OVER; keeps every row.
- Group total on each row
- SUM(x) OVER (PARTITION BY g).
- Running aggregate
- With ORDER BY: SUM / COUNT / AVG up to the current row.
- COUNT(*) OVER ()
- Total rows in the result, repeated on each row (handy for pagination).
Visual diagram
Theory & example queries
Group values on every row
Without ORDER BY, the window is the whole partition, so AVG(salary) OVER (PARTITION BY dept) is the department average repeated on each employee's row. That makes comparisons easy: salary - AVG(salary) OVER (PARTITION BY dept) is each person's difference from their department average, and amount / SUM(amount) OVER () is each row's share of the grand total.
COUNT(*) OVER () returns the total number of result rows on every row, which lets a paginated API return the total count with the first page in a single query (computed before LIMIT is applied).
SELECT name, dept, salary, ROUND( salary - AVG(salary) OVER ( PARTITION BY dept ), 0 ) AS vs_dept_avgFROM employees;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| name | dept | salary | vs_dept_avg |
|---|---|---|---|
| Asha | Engineering | 90000 | 5000 |
| Bikram | Engineering | 80000 | -5000 |
| Chen | Sales | 75000 | 0 |
Note: Representative sample employees; actual values and rounding depend on the stored salaries and numeric type.
Key takeaway: PARTITION BY without ORDER BY = group totals on every row.
Running versions and limits
Add ORDER BY and the default frame becomes "start of partition to current row", giving running counts and sums: COUNT(*) OVER (PARTITION BY customer_id ORDER BY created_at) numbers each customer's orders (ties share a count unless you use ROWS). Add an explicit frame for moving aggregates such as a 7-day sum.
PostgreSQL and SQL Server don't support DISTINCT inside window aggregates, so COUNT(DISTINCT user_id) OVER (…) fails. Work around it with a DENSE_RANK trick (MAX(DENSE_RANK() …)) or a GROUP BY joined back; BigQuery and some other engines do support it. Window aggregates also need the partition's rows in memory or sorted, so very large partitions can spill to disk.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT customer_id, created_at, COUNT(*) OVER ( PARTITION BY customer_id ORDER BY created_at, id ROWS UNBOUNDED PRECEDING ) AS order_numberFROM orders;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output4 sample rows
| customer_id | created_at | order_number |
|---|---|---|
| 42 | 2026-10-03 09:15:00 | 1 |
| 42 | 2026-10-18 14:20:00 | 2 |
| 77 | 2026-10-05 11:00:00 | 1 |
| 77 | 2026-11-02 16:45:00 | 2 |
Note: Illustrative orders; the running number resets for each customer and follows created_at, then id.
Key takeaway: ORDER BY makes them running; DISTINCT isn't allowed in PostgreSQL window aggregates.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Pick the aggregate
Choose SUM, AVG, COUNT, MIN or MAX for the group value you need.
SUM(amount)
When to use it & trade-offs
What it is
Ordinary aggregates (SUM, AVG, COUNT, MIN, MAX) become window functions when you add OVER: SUM(amount) OVER (PARTITION BY customer_id) puts each customer's total on every one of their rows, without collapsing them. With ORDER BY inside OVER they become running aggregates, and with a frame they become moving ones.
Why it matters: "Show each order with the customer's total", "each product's share of its category", "each employee versus the department average": these need detail rows and group aggregates side by side. Window aggregates do it in one pass, without joining a GROUP BY back to the table.
When to reach for it
- Share of total per row
- Difference from the group average
- Total row count alongside paginated results
When to avoid or be careful
- Adding ORDER BY when you wanted a plain group total
- COUNT(DISTINCT …) OVER in PostgreSQL or SQL Server
- Using DISTINCT to collapse window results into one row per group (use GROUP BY)
Window aggregate vs GROUP BY vs join-back
Strengths: One pass; no join; keeps every row.
Watch out: No DISTINCT in PostgreSQL; large partitions can be memory-heavy.
Strengths: Smallest result.
Watch out: Detail rows are gone.
Strengths: Works everywhere; supports DISTINCT.
Watch out: Two passes and more code.
Interview signals & numbers to know
When this topic comes up
- “Each order with the customer's total”
- “Percentage of category sales”
- “Compare each employee with the department average”
- Total count with pagination
- SUM OVER
Benchmarks & rules of thumb
- 5
- common window aggregates: SUM, AVG, COUNT, MIN, MAX
- OVER ()
- whole-result totals
- 0
- DISTINCT support in PostgreSQL window aggregates
Common mistakes & follow-ups
Common interview mistakes
- Dividing integers for a share and getting 0 on every row.
- Writing COUNT(DISTINCT user_id) OVER (…) in PostgreSQL and getting an error.
- Adding ORDER BY by habit and turning a total into a running total.
Likely interviewer follow-ups
- How would you show each product's share of its category's revenue?
- How do you get a distinct count per group on every row in PostgreSQL?
- How would you return the total row count together with a paginated page?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Aggregate Window Functions (SUM() OVER, AVG() OVER, COUNT() OVER) with hands-on SQL practice and interview Q&A.