Window Functions in SQL

đŸĒŸ 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

Window functions are widely used for rankings, running totals, moving averages, comparisons between rows, and analytical reporting.

đŸŽ¯ 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

EmployeeIDEmployeeNameDepartmentSalary
101AliceSales60000
102BobSales55000
103CharlieIT75000
104DavidIT70000

📝 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.

ClausePurpose
OVER()Creates the window for the function.
PARTITION BYDivides rows into independent groups.
ORDER BYDefines the order within each partition.
Window FrameDefines which rows are included in the calculation.

Remember

PARTITION BY is similar to GROUP BY, but it does not collapse multiple rows into one.

💡 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

EmployeeDepartmentSalaryDepartment Average
AliceSales6000057500
BobSales5500057500
CharlieIT7500072500
DavidIT7000072500

📚 Common Window Functions

FunctionPurpose
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 FunctionsGROUP 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 SystemWindow 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

Some window functions require a well-defined ordering to produce meaningful and deterministic results. Review the default window frame behavior in your database system, especially when using functions such as LAST_VALUE().

âš ī¸ Best Practices

Best Practice

Use window functions for analytical queries instead of complex self-joins, include ORDER BY whenever row sequence matters, partition data appropriately, choose descriptive aliases for calculated columns, and understand how window frames influence aggregate window functions.

🚀 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.
>>"Window functions let you analyze data across rows without losing the detail of each individual row."

Summary

✅ Window functions are one of SQL's most powerful analytical features. They allow calculations across related rows while preserving every row in the result set. By using the OVER clause with PARTITION BY and ORDER BY, you can efficiently perform rankings, running totals, moving averages, and many other advanced analyses without complex SQL queries.