Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Prior to modern SQL standards, aggregating data inevitably meant collapsing multiple rows into a single summary row using GROUP BY. If you wanted to view an individual employee's salary alongside their department's average salary, you had to write awkward self-joins or correlated subqueries.
Window Functions (introduced in MySQL 8.0) completely revolutionize SQL analytics. A window function performs a calculation across a set of table rows that are related to the current row, without collapsing the individual rows!
| Characteristic | GROUP BY Aggregation | Window Function (OVER()) |
|---|---|---|
| Row Count | Collapses rows (returns 1 row per group) | Preserves all individual rows (returns N rows) |
| Output Detail | Individual row details are discarded | Individual row details are retained alongside calculations |
| Syntax | SELECT dept, AVG(salary) ... GROUP BY dept | SELECT name, salary, AVG(salary) OVER(PARTITION BY dept) |
| Primary Use Case | High-level summary reports | Running totals, rankings, moving averages, row-by-row comparisons |
Suppose we have an employees table:
| emp_id | name | department | salary |
|---|---|---|---|
| 1 | Alice | IT | 90000 |
| 2 | Bob | IT | 80000 |
| 3 | Carol | HR | 60000 |
| 4 | Dave | HR | 65000 |
Result (Rows are collapsed from 4 to 2):
Result (All 4 rows preserved!):
| emp_id | name | department | salary | dept_avg_sal |
|---|---|---|---|---|
| 1 | Alice | IT | 90000 | 85000 |
| 2 | Bob | IT | 80000 | 85000 |
| 3 | Carol | HR | 60000 | 62500 |
| 4 | Dave | HR | 65000 | 62500 |
Alice can immediately compare her $90,000 salary against her department's $85,000 average directly on row 1!
Every window function call consists of:
SUM, AVG, COUNT, MIN, MAX) or a dedicated window function (ROW_NUMBER, RANK, DENSE_RANK, LEAD, LAG).OVER() Clause: Indicates that the function operates as a window function rather than a standard aggregate.Window functions execute very late in the SQL processing pipeline:
FROM and JOINWHEREGROUP BY and HAVINGOVER)SELECT expressionsDISTINCTORDER BYLIMITWHERE clause, you cannot put a window function directly in a WHERE filter (e.g., WHERE ROW_NUMBER() OVER(...) <= 5 will fail). To filter on window function results, wrap the query in a CTE or derived table!Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| CTEs vs Subqueries vs Views Comparison | The OVER() Clause & PARTITION BY Mechanics |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.