Window Functions: When to Use OVER() Instead of GROUP BY

โฑ๏ธ 35 sec read ๐Ÿ“Š SQL

Window functions let you perform calculations across rows while keeping individual row details. GROUP BY collapses rows.

The Key Difference

GROUP BY aggregates rows into groups (reduces row count):

SELECT department, AVG(salary) as avg_salary
FROM employees
GROUP BY department;
-- Returns one row per department

Window Functions calculate across rows while preserving all rows:

SELECT name, department, salary,
       AVG(salary) OVER (PARTITION BY department) as dept_avg
FROM employees;
-- Returns all employee rows with department average

When to Use Window Functions

Practical Example: Top Salaries by Department

SELECT name, department, salary,
       RANK() OVER (PARTITION BY department ORDER BY salary DESC) as rank
FROM employees
WHERE rank <= 3;
-- Get top 3 earners per department

Remember: Use GROUP BY when you want summary statistics. Use window functions when you need both detail rows AND aggregate calculations.

โ† Back to SQL Tips