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 81/ 160
05. Window Functions & Analytical SQL

Window Functions vs GROUP BY Aggregations (Preserving Row Granularity)

Use windows when you need aggregates without collapsing detail rows.

BeginnerOVER · Grain · Aggregates3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

GROUP BY squashes rows into one per group. A window function keeps all the rows and writes the group's answer on each.

Think of it like…

A class's exam results: GROUP BY gives you one summary line per class ("Class A: average 72"). A window function gives every student's line with the class average printed next to their own mark.

Where you’ve seen it

SELECT name, dept, salary, AVG(salary) OVER (PARTITION BY dept) AS dept_avg, salary - AVG(salary) OVER (PARTITION BY dept) AS diff FROM employees;: every employee, their department average, and how far above or below it they are.

Words you’ll hear

Row grain
Whether the output has one row per group (GROUP BY) or one per original row (window).
OVER ()
Turns an aggregate into a window function; empty parentheses mean the whole result set.
PARTITION BY
The window's equivalent of GROUP BY: which rows each calculation looks at.
Evaluation order
Window functions run after WHERE, GROUP BY and HAVING.

Visual diagram

Loading interactive diagram

Theory & example queries

Choosing between them

If the answer should have one row per group (revenue per month), use GROUP BY. If each detail row should stay and be compared with its group (each order versus the customer's average), use a window function with PARTITION BY on the same columns you'd have grouped by.

Without window functions, the detail-plus-aggregate shape needs a GROUP BY subquery joined back to the detail table. That works, but it's longer and reads the table twice.

Each order as a share of the customer's totalQuery 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  order_id,3  customer_id,4  amount,5  amount / SUM(amount) OVER (6    PARTITION BY7      customer_id8  ) AS share9FROM10  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/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Orders as shares of customer totals3 sample rows
Orders as shares of customer totals
order_idcustomer_idamountshare
10176000.6
10274000.4
20182501

Note: Assumes a 1,000 total for customer 7 and a 250 total for customer 8; all source rows remain visible with a window SUM.

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

Key takeaway: Summary → GROUP BY; detail with group context → window.

Using both in one query

Window functions are evaluated after GROUP BY, so they can operate on grouped results. SELECT dept, SUM(salary) AS total, SUM(SUM(salary)) OVER () AS company_total FROM employees GROUP BY dept gives each department's total next to the company total, and dividing them gives each department's share.

Because they run after WHERE, you can't filter on a window result in the same query's WHERE. Compute it in a CTE and filter outside, which is the standard pattern for "rows above their group's average".

Employees paid above their 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
1WITH2  x AS (3    SELECT4      name,5      salary,6      AVG(salary) OVER (7        PARTITION BY8          dept9      ) AS dept_avg10    FROM11      employees12  )13SELECT14  name15FROM16  x17WHERE18  salary > dept_avg;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/18
3OutputInspect the representative rows, affected-row count, plan, or command status.
Above-average employees2 sample rows
Above-average employees
name
Priya
Sam

Note: Representative salaries where the returned employees earn more than the AVG(salary) for their department.

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

Key takeaway: Windows run after grouping; filter their results in an outer query.

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 1Design

Decide the output grain

Ask whether the result needs one row per group or one row per original record.

Focus at this step

per department vs per employee

What to watch at this step
Per group
GROUP BY
Per row
window
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

GROUP BY collapses each group into a single row. A window function (AVG(salary) OVER (PARTITION BY dept)) computes the same kind of aggregate but keeps every original row, attaching the group's value to each one. Same maths, different shape of result.

Why it matters: Questions like "show each employee with their department's average" or "each order as a percentage of the customer's total" need detail rows and group aggregates together. GROUP BY alone can't do it without joining back; a window function does it in one pass. Knowing which one fits is a basic SQL interview check.

When to reach for it

  • Each row next to its group's average, total or count
  • Percent of total per row
  • Rows above or below their group's average

When to avoid or be careful

  • GROUP BY plus a join back when a window function would do
  • Window functions when you actually want one row per group (you'd need DISTINCT to undo the duplication)
  • Filtering on a window result in the same WHERE

GROUP BY vs window function vs join-back

GROUP BY
Best for: Summary tables: one row per group

Strengths: Smallest result; exactly what a report needs.

Watch out: Loses the detail rows.

Window function
Best for: Each row compared with its group

Strengths: One pass, keeps every row, no extra join.

Watch out: Results can't be filtered in the same WHERE.

GROUP BY subquery joined back
Best for: Engines without window functions

Strengths: Works everywhere.

Watch out: Longer and reads the table twice.

Interview signals & numbers to know

When this topic comes up

  • “Show each employee with their department's average”
  • “Percentage of total”
  • “Above the group average”
  • OVER (PARTITION BY …)
  • Keep detail rows

Benchmarks & rules of thumb

GROUP BY -
rows = number of groups
Window -
rows = number of input rows
OVER () -
one window over everything

Common mistakes & follow-ups

Common interview mistakes

  • Using a window function and then adding DISTINCT to get one row per group, when GROUP BY was the right tool.
  • Trying to select a detail column with GROUP BY and getting the "must appear in GROUP BY" error.
  • Filtering WHERE salary > AVG(salary) OVER (…) in the same query level.

Likely interviewer follow-ups

  • How would you show each product's sales and its share of its category's sales?
  • Can you use a window function together with GROUP BY in one query?
  • Why can't you filter on a window function in WHERE?
Interview tip: Explain the difference by the number of rows each returns, using one small table. Then give the "above department average" query as your example, since it uses the CTE-and-filter pattern too.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Window Functions vs GROUP BY Aggregations (Preserving Row Granularity) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Structuring Production Analytical SQL Models
Next topic
Anatomy of OVER() Clause (PARTITION BY, ORDER BY, Window Frame)