Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 87/ 160
05. Window Functions & Analytical SQL

Aggregate Window Functions (SUM() OVER, AVG() OVER, COUNT() OVER)

Apply SUM/AVG/COUNT as windows to annotate every detail row.

BeginnerSUM OVER · AVG OVER3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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).

Above or below the department averageQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  name,3  dept,4  salary,5  ROUND(6    salary - AVG(salary) OVER (7      PARTITION BY8        dept9    ),10    011  ) AS vs_dept_avg12FROM13  employees;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
namedeptsalaryvs_dept_avg
AshaEngineering900005000
BikramEngineering80000-5000
ChenSales750000

Note: Representative sample employees; actual values and rounding depend on the stored salaries and numeric type.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Running order count per customerQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id,3  created_at,4  COUNT(*) OVER (5    PARTITION BY6      customer_id7    ORDER BY8      created_at,9      id ROWS UNBOUNDED PRECEDING10  ) AS order_number11FROM12  orders;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
customer_idcreated_atorder_number
422026-10-03 09:15:001
422026-10-18 14:20:002
772026-10-05 11:00:001
772026-11-02 16:45:002

Note: Illustrative orders; the running number resets for each customer and follows created_at, then id.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: ORDER BY makes them running; DISTINCT isn't allowed in PostgreSQL window aggregates.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Function

Pick the aggregate

Choose SUM, AVG, COUNT, MIN or MAX for the group value you need.

Focus at this step

SUM(amount)

What to watch at this step
Same
as GROUP BY functions
Tip: use ← → to move between steps

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

Window aggregate
Best for: Detail rows with group context

Strengths: One pass; no join; keeps every row.

Watch out: No DISTINCT in PostgreSQL; large partitions can be memory-heavy.

GROUP BY
Best for: One summary row per group

Strengths: Smallest result.

Watch out: Detail rows are gone.

GROUP BY joined back to the table
Best for: COUNT(DISTINCT) per group on detail rows; engines without windows

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?
Interview tip: Use the share-of-customer example: it shows PARTITION BY, keeps rows, and involves a division (where you can mention casting). Three points in one query.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Value Functions: FIRST_VALUE(), LAST_VALUE(), NTH_VALUE()
Next topic
Window Frame Clauses (ROWS vs RANGE vs GROUPS)