GROUP BY vs Window Functions in SQL (Beginner-Friendly Explanation)

One of the most important SQL concepts for beginners is understanding the difference between
πŸ‘‰ GROUP BY and Window Functions (OVER()).

They may look similar, but they solve very different problems.

Let’s understand this slowly, with simple tables.


🧠 The Core Difference (In One Line)

  • GROUP BY β†’ Reduces rows
  • Window Function β†’ Keeps all rows

πŸ“Š Sample Data

day amount
Day 1 100
Day 2 150
Day 3 200

❌ Using GROUP BY

Question:

πŸ‘‰ What is the total amount?

SELECT SUM(amount)
FROM sales;

Result:

450

βœ” Correct total
❌ But all rows are collapsed into one row

You lose row-level details like Day 1, Day 2, Day 3.


βœ… Using a Window Function

Same question, different need:

πŸ‘‰ Show the total along with each row

SELECT
  day,
  amount,
  SUM(amount) OVER () AS total_amount
FROM sales;

Result:

day amount total_amount
Day 1 100 450
Day 2 150 450
Day 3 200 450

βœ” Total is shown
βœ” All rows are preserved


πŸ” Why This Matters

GROUP BY is good when:

  • You want summary data
  • You don’t care about individual rows

Example:

  • Total sales
  • Average salary per department

Window Functions are good when:

  • You need both detail and summary
  • You want calculations per row

Example:

  • Running totals
  • Rank within department
  • Opening vs closing balance

πŸ“Œ Another Common Example

Average salary per department

GROUP BY

SELECT department, AVG(salary)
FROM employees
GROUP BY department;

βœ” One row per department


Window Function

SELECT
  employee,
  department,
  salary,
  AVG(salary) OVER (PARTITION BY department) AS dept_avg
FROM employees;

βœ” Every employee row stays
βœ” Department average is visible


🧠 Easy Way to Remember

If rows disappear β†’ GROUP BY
If rows stay β†’ Window Function


🎯 Interview Tip

If a question says:

  • β€œShow each row along with…” β†’ Think window function
  • β€œGive me one result per group” β†’ Think GROUP BY

One-Line Summary

GROUP BY summarizes data.
Window functions analyze data without losing rows.