đĒ Window Functions are advanced SQL functions that perform calculations across a set of rows related to the current row without grouping the rows into a single result. Unlike aggregate functions used with GROUP BY, window functions return a value for every row while still allowing access to the surrounding rows.
đ What are Window Functions?
A window function operates on a window (or partition) of rows defined by the OVER clause. Each row is processed individually, but the calculation considers other rows within the same partition or ordered sequence.
Information
đ¯ Why Use Window Functions?
Window functions make analytical queries simpler and more efficient without requiring complex subqueries or self-joins.
- đ Calculate running totals.
- đ Rank rows within groups.
- đ Compare current and previous rows.
- đ Calculate moving averages.
- đ Preserve every row in the result set.
đ Sample Table
| EmployeeID | EmployeeName | Department | Salary |
|---|---|---|---|
| 101 | Alice | Sales | 60000 |
| 102 | Bob | Sales | 55000 |
| 103 | Charlie | IT | 75000 |
| 104 | David | IT | 70000 |
đ Basic Syntax
General Window Function Syntax
SELECT
column_name,
window_function() OVER (
PARTITION BY column_name
ORDER BY column_name
) AS result
FROM table_name;đĒ Understanding the OVER Clause
The OVER clause defines the window used by the function.
| Clause | Purpose |
|---|---|
| OVER() | Creates the window for the function. |
| PARTITION BY | Divides rows into independent groups. |
| ORDER BY | Defines the order within each partition. |
| Window Frame | Defines which rows are included in the calculation. |
Remember
đĄ Example: Ranking Employees
ROW_NUMBER() Example
SELECT
EmployeeName,
Department,
Salary,
ROW_NUMBER() OVER (
PARTITION BY Department
ORDER BY Salary DESC
) AS RankNumber
FROM Employees;Each department receives its own ranking based on salary, while every employee remains in the result set.
đĄ Example: Running Total
Running Total
SELECT
EmployeeName,
Salary,
SUM(Salary) OVER (
ORDER BY EmployeeID
) AS RunningTotal
FROM Employees;The running total increases as each employee row is processed.
đĄ Example: Department Average Salary
Average Salary per Department
SELECT
EmployeeName,
Department,
Salary,
AVG(Salary) OVER (
PARTITION BY Department
) AS DepartmentAverage
FROM Employees;Every employee row displays the average salary for its department without using GROUP BY.
đ Example Output
| Employee | Department | Salary | Department Average |
|---|---|---|---|
| Alice | Sales | 60000 | 57500 |
| Bob | Sales | 55000 | 57500 |
| Charlie | IT | 75000 | 72500 |
| David | IT | 70000 | 72500 |
đ Common Window Functions
| Function | Purpose |
|---|---|
| ROW_NUMBER() | Assigns a unique row number. |
| RANK() | Ranks rows with gaps for ties. |
| DENSE_RANK() | Ranks rows without gaps. |
| NTILE() | Divides rows into equal groups. |
| LAG() | Accesses a previous row. |
| LEAD() | Accesses a following row. |
| FIRST_VALUE() | Returns the first value in the window. |
| LAST_VALUE() | Returns the last value in the window. |
| SUM(), AVG(), COUNT(), MIN(), MAX() | Aggregate functions used as window functions. |
âī¸ Window Functions vs GROUP BY
| Window Functions | GROUP BY |
|---|---|
| Returns every row. | Returns one row per group. |
| Performs calculations across related rows. | Aggregates rows into summary results. |
| Uses the OVER clause. | Uses the GROUP BY clause. |
| Ideal for analytics. | Ideal for summaries. |
đŧ Real-World Applications
- đ Rank employees by salary.
- đ Calculate cumulative sales.
- đ Generate moving averages.
- đĻ Analyze financial trends over time.
- đ Compare current and previous orders.
- đĻ Build business intelligence reports.
đī¸ Database Compatibility
| Database System | Window Function Support |
|---|---|
| MySQL | â Supported (MySQL 8.0 and later). |
| PostgreSQL | â Extensive support. |
| SQL Server | â Extensive support. |
| Oracle | â Extensive support. |
| SQLite | â Supported (SQLite 3.25.0 and later). |
â ī¸ Common Mistakes
- â Confusing PARTITION BY with GROUP BY.
- â Forgetting to include ORDER BY when row order affects the calculation.
- â Ignoring the default window frame, which can affect functions such as LAST_VALUE().
- â Using window functions where a simple aggregate query would be more appropriate.
Warning
â ī¸ Best Practices
Best Practice
đ Key Points to Remember
- đ Window functions perform calculations across related rows.
- đ They preserve every row in the result set.
- đ They use the OVER clause.
- đ PARTITION BY creates independent windows.
- đ ORDER BY defines row sequence within a window.
- đ They are ideal for rankings, running totals, comparisons, and analytical reporting.