What are Window Functions in SQL?
Window Functions in SQL are special functions that perform calculations across a set of rows related to the current row without grouping the rows into a single output.
In simple words:
Window functions allow calculations like ranking, running totals, averages, and comparisons while still keeping individual rows visible.
Why Window Functions are Important
Enterprise applications require:
- Ranking systems
- Analytics dashboards
- Running totals
- Performance analysis
- Comparative reporting
Window functions help:
- Perform advanced analytics
- Avoid complex subqueries
- Generate efficient reports
- Analyze row-by-row data
Simple Real-Life Example
Think about:
- Ranking students by marks
You want:
- Each student record visible
- Ranking beside each row
Without Window Functions
Complex joins and subqueries may be required.
With Window Functions
Simple and efficient query possible.
Window Function Internal Architecture
Rows Selected
|
v
Window Created
|
v
Function Applied Across Related Rows
|
v
Result Added to Each Row
Main Feature of Window Functions
Unlike GROUP BY:
- Window functions do NOT collapse rows
GROUP BY Example
SELECT department,
AVG(salary)
FROM employees
GROUP BY department;
Result
One row per department.
Window Function Example
SELECT employee_name,
department,
salary,
AVG(salary) OVER (
PARTITION BY department
) AS dept_avg_salary
FROM employees;
Result
Every employee row remains visible with department average added.
Window Function Syntax
SELECT column_name,
window_function() OVER (
PARTITION BY column_name
ORDER BY column_name
)
FROM table_name;
Main Components of Window Functions
- Window Function
- OVER Clause
- PARTITION BY
- ORDER BY
1. OVER Clause
OVER defines:
- The window of rows for calculation
Example
AVG(salary) OVER ()
Meaning
Average calculated across:
- Entire result set
2. PARTITION BY
PARTITION BY divides:
- Rows into groups
Example
AVG(salary) OVER (
PARTITION BY department
)
Meaning
Average salary calculated:
- Separately for each department
3. ORDER BY
ORDER BY defines:
- Row order inside window
Example
SUM(salary) OVER (
ORDER BY salary
)
Meaning
Running total based on salary order.
Types of Window Functions
- Ranking Functions
- Aggregate Window Functions
- Value Functions
1. Ranking Functions
Used for:
- Assigning ranks
Common Ranking Functions
- ROW_NUMBER()
- RANK()
- DENSE_RANK()
- NTILE()
ROW_NUMBER Example
SELECT employee_name,
salary,
ROW_NUMBER() OVER (
ORDER BY salary DESC
) AS row_num
FROM employees;
Result
Unique row numbers assigned.
RANK Example
SELECT employee_name,
salary,
RANK() OVER (
ORDER BY salary DESC
) AS employee_rank
FROM employees;
Important Point
RANK skips numbers for duplicate values.
DENSE_RANK Example
SELECT employee_name,
salary,
DENSE_RANK() OVER (
ORDER BY salary DESC
) AS employee_rank
FROM employees;
Important Point
DENSE_RANK does not skip ranking numbers.
2. Aggregate Window Functions
Used for:
- Calculations across windows
Common Aggregate Window Functions
- SUM()
- AVG()
- COUNT()
- MIN()
- MAX()
Running Total Example
SELECT employee_name,
salary,
SUM(salary) OVER (
ORDER BY employee_id
) AS running_total
FROM employees;
What Happens?
Running cumulative salary total generated.
Running Total Visualization
Salary: 1000 → Total 1000 Salary: 2000 → Total 3000 Salary: 3000 → Total 6000
Department Average Example
SELECT employee_name,
department,
salary,
AVG(salary) OVER (
PARTITION BY department
) AS dept_avg
FROM employees;
3. Value Functions
Used for:
- Accessing row values
Common Value Functions
- LAG()
- LEAD()
- FIRST_VALUE()
- LAST_VALUE()
LAG Function
Returns:
- Previous row value
LAG Example
SELECT employee_name,
salary,
LAG(salary) OVER (
ORDER BY employee_id
) AS previous_salary
FROM employees;
LEAD Function
Returns:
- Next row value
LEAD Example
SELECT employee_name,
salary,
LEAD(salary) OVER (
ORDER BY employee_id
) AS next_salary
FROM employees;
Window Frame Concept
Window frame defines:
- Subset of rows inside partition
Example
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
Meaning
Calculate from:
- First row to current row
Window Function Query Flow
Select Rows
|
v
Partition Rows
|
v
Sort Rows
|
v
Apply Window Function
|
v
Return Results with Original Rows
Window Functions vs GROUP BY
| Feature | Window Functions | GROUP BY |
|---|---|---|
| Original Rows | Preserved | Collapsed |
| Analytics | Advanced | Basic Aggregation |
| Ranking Support | Yes | No |
| Running Totals | Easy | Difficult |
Real-Time Banking Example
Banking systems use window functions for:
- Top customers ranking
- Transaction analysis
- Balance trend analysis
Example
Find top 5 customers by account balance.
Real-Time E-Commerce Example
E-commerce platforms use window functions for:
- Sales leaderboards
- Revenue analysis
- Product ranking
Example
Rank products by monthly sales.
Real-Time Learning Platform Example
Learning platforms use window functions for:
- Student rankings
- Progress tracking
- Department-wise toppers
Example
Find top students in each course.
Window Functions in Microservices
Microservices use window functions for:
- Analytics APIs
- Reporting dashboards
- Recommendation systems
Advantages of Window Functions
- Powerful analytics support
- Preserves original rows
- Reduces complex subqueries
- Improves reporting capabilities
Disadvantages of Window Functions
- Complex syntax for beginners
- Sorting operations may impact performance
- High memory usage on large datasets
Performance Consideration
Window functions require:
- Sorting
- Partitioning
which may:
- Increase execution cost on large tables
Best Practices
- Use indexes on partition and order columns
- Avoid unnecessary partitions
- Optimize large analytical queries
- Use proper window frames
Common Interview Mistake
Many developers think:
- Window functions work same as GROUP BY
Reality
Window functions:
- Preserve original rows
while GROUP BY:
- Aggregates rows into groups
Related Learning Topics
- Difference Between RANK and DENSE_RANK
- What is ROW_NUMBER in SQL?
- What is PARTITION BY in SQL?
- What is GROUP BY in SQL?
- MySQL Performance Optimization
Professional Interview Answer
Window Functions in SQL are analytical functions that perform calculations across a set of related rows while preserving the original rows in the result set. They operate using the OVER clause, optionally combined with PARTITION BY and ORDER BY clauses. Window functions are widely used for ranking, running totals, moving averages, row comparisons, and advanced reporting. Common window functions include ROW_NUMBER, RANK, DENSE_RANK, SUM, AVG, LAG, and LEAD. Unlike GROUP BY, window functions do not collapse rows, making them extremely useful for enterprise analytics, dashboards, banking systems, e-commerce reporting, and microservices-based analytical APIs.
Why Interviewers Like This Answer
- Clearly explains analytical processing
- Includes OVER and PARTITION BY concepts
- Shows advanced SQL expertise
- Provides enterprise-level examples
- Explains GROUP BY vs Window Functions differences
Frequently Asked Questions
What are window functions in SQL?
Window functions perform calculations across related rows while preserving original rows.
What is the purpose of OVER clause?
OVER defines the window of rows used for calculation.
What is PARTITION BY?
PARTITION BY divides rows into groups for window calculations.
What is the difference between GROUP BY and window functions?
GROUP BY collapses rows, while window functions preserve original rows.
What are common window functions?
ROW_NUMBER, RANK, DENSE_RANK, SUM, AVG, LAG, and LEAD.