6.1 Window Functions: OVER(), PARTITION BY & GROUP BY vs Window
Unlock the #1 skill that separates junior from senior SQL engineers: Window Functions. Learn how OVER() and PARTITION BY compute department averages and percentages WITHOUT collapsing individual rows.
1. GROUP BY vs Window Functions — The Crucial Visual Difference
With GROUP BY, 100 employee rows collapse into 5 department summary rows — you lose every individual employee's name and salary.
With a Window Function (OVER (...)), SQL computes the department aggregate and attaches it right next to every single employee row — 0 rows are collapsed!
| Dimension | GROUP BY | Window Function (OVER (...)) |
|---|---|---|
| Output Row Count | Collapses to 1 row per group | Identical to input row count |
| Keeps Row-Level Columns? | ❌ Only grouped columns allowed | ✅ Keeps emp_id, name, salary, etc.! |
| When Does It Execute? | Step 3 (before HAVING) | Step 5 (during SELECT) — after WHERE, GROUP BY, HAVING! |
Can Filter Directly in WHERE? | ❌ No (use HAVING) | ❌ No (wrap in a CTE, then filter in outer WHERE!) |
2. Anatomy of a Window Function
function_name(...) OVER (
PARTITION BY group_column -- Optional: splits rows into independent windows (like GROUP BY)
ORDER BY sort_column DESC -- Optional: orders rows inside each window
)
Real-World Example: Compare Every Employee Against Their Department Average!
SELECT
name,
dept,
salary,
ROUND(AVG(salary) OVER (PARTITION BY dept), 0) AS dept_avg,
salary - ROUND(AVG(salary) OVER (PARTITION BY dept), 0) AS diff_from_avg,
ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY dept), 1) AS pct_of_dept_payroll
FROM employees
ORDER BY dept, salary DESC;
- Notice
OVER ()(empty parentheses!) treats the entire result set as one single window — e.g.,SUM(salary) OVER ()gives the company-wide grand total on every row!
3. Watch AVG() OVER (PARTITION BY dept) Execute Live
| name | dept | salary |
|---|---|---|
| Aarav | Eng | 120000 |
| Kabir | Eng | 160000 |
| Meera | Sales | 80000 |
| Riya | Sales | 100000 |
4. Quick Check Your Understanding
Module 6.1 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.