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.
Comments (0)
No comments yet. Be the first to share your thoughts!
Leave a Comment