SQL Window Functions with Examples: A Complete Beginner’s Guide
Introduction
Have you ever needed to calculate employee rankings, compare monthly sales, or find running totals without losing individual records? SQL window functions make these tasks easier.
SQL Window Functions allow you to perform calculations across related rows while keeping each original row in the query result. Unlike regular aggregate functions, they do not combine multiple records into a single result.
For example, a company may want to identify the highest-paid employee in every department. It may also need to compare each employee’s salary with the department average. Window functions help analysts answer these questions using simple SQL queries.
These functions are useful in Data Analytics, reporting, financial analysis, and database development. Furthermore, they are important concepts for anyone learning Oracle SQL and PL/SQL.
In this guide, you will learn how window functions work, understand their different types, and practise SQL queries using employee and sales datasets. Whether you are a student, fresher, or working professional, these examples will help you build practical database skills.
Table of Contents
- What Are SQL Window Functions?
- How Do SQL Window Functions Work?
- What Are the Main Types of Window Functions?
- Practical SQL Window Functions with Examples
- What Is the Difference Between GROUP BY and Window Functions?
- Where Are Window Functions Used in Real Projects?
- Common Mistakes to Avoid
- How Can Beginners Learn SQL Window Functions?
- Frequently Asked Questions
What Are SQL Window Functions?
SQL window functions perform calculations across a group of related rows without reducing the number of rows in the result.
In simple terms, they allow you to calculate rankings, averages, totals, and comparisons while displaying individual records.
For example, consider an employee table containing employee names, departments, and salaries. You can calculate the average salary for each department and display it alongside every employee.
A window function uses the OVER() clause to define which rows participate in its calculation.
Basic syntax:
SELECT
column_name,
function_name() OVER (
PARTITION BY column_name
ORDER BY column_name
) AS result
FROM table_name;
The OVER() clause defines the window used by the function. It can contain partitioning, ordering, and an optional window frame.
How Do SQL Window Functions Work?
SQL window functions work by evaluating related rows within a specified window.
Three important concepts help you understand their behaviour.
1. OVER() Clause
The OVER() clause tells SQL which rows to consider for a calculation.
For example:
SELECT
employee_name,
salary,
AVG(salary) OVER () AS average_salary
FROM employees;
This query calculates the average salary across all employees. However, it displays the average alongside every employee record.
2. PARTITION BY
PARTITION BY divides records into separate groups based on one or more columns.
For example:
SELECT
employee_name,
department,
salary,
AVG(salary) OVER (
PARTITION BY department
) AS department_average
FROM employees;
Here, SQL calculates a separate average for each department. Furthermore, every employee retains their individual record.
3. ORDER BY
ORDER BY defines the order in which SQL evaluates rows within a window.
For example:
SELECT
employee_name,
salary,
ROW_NUMBER() OVER (
ORDER BY salary DESC
) AS employee_rank
FROM employees;
This query assigns a sequential number based on salary, starting with the highest-paid employee.
Together, these three concepts form the foundation of SQL window functions.
What Are the Main Types of SQL Window Functions?
SQL window functions generally fall into three useful groups: ranking functions, aggregate window functions, and value or navigation functions.
| Function Category | Common Functions | Main Purpose |
|---|---|---|
| Ranking | ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE() | Assign rankings or groups |
| Aggregate | SUM(), AVG(), COUNT(), MIN(), MAX() | Calculate totals and summaries |
| Navigation | LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE() | Access values from related rows |
Let’s understand each category with practical examples.
1. Ranking Functions
Ranking functions assign numbers or positions to records based on specified ordering.
ROW_NUMBER()assigns a unique sequential number to each row.RANK()assigns rankings but leaves gaps after tied values.DENSE_RANK()assigns rankings without leaving gaps.NTILE()divides ordered rows into a specified number of groups.
2. Aggregate Window Functions
Aggregate functions calculate values across related records.
Common examples include:
SUM()– Calculates a total.AVG()– Calculates an average.COUNT()– Counts records.MAX()– Finds the highest value.MIN()– Finds the lowest value.
3. Navigation Functions
Navigation functions help compare the current record with other records in the same window.
For example:
LAG()accesses a previous row’s value.LEAD()accesses a following row’s value.FIRST_VALUE()returns the first value in a window frame.LAST_VALUE()returns the last value in a window frame.
These functions are particularly useful for comparing sales and tracking changes over time.
Practical SQL Window Functions with Examples
Let’s understand SQL window functions using a practical employee dataset.
Consider the following employee records:
| Employee ID | Name | Department | Salary |
|---|---|---|---|
| 101 | Arun | IT | 50000 |
| 102 | Priya | HR | 35000 |
| 103 | Kumar | IT | 60000 |
| 104 | Divya | HR | 45000 |
| 105 | Ravi | IT | 60000 |
Example 1: How Does ROW_NUMBER() Work?
ROW_NUMBER() assigns a unique number to every row based on the selected sorting order.
SELECT
employee_name,
salary,
ROW_NUMBER() OVER (
ORDER BY salary DESC, employee_id
) AS row_num
FROM employees;
Result:
| Employee | Salary | Row Number |
|---|---|---|
| Kumar | 60000 | 1 |
| Ravi | 60000 | 2 |
| Arun | 50000 | 3 |
| Divya | 45000 | 4 |
| Priya | 35000 | 5 |
Notice that Kumar and Ravi have the same salary. However, ROW_NUMBER() assigns different numbers because the employee ID provides a secondary sorting rule.
Example 2: What Is the Difference Between RANK() and DENSE_RANK()?
RANK() and DENSE_RANK() assign the same rank to tied values. However, their treatment of the next rank differs.
SELECT
employee_name,
salary,
RANK() OVER (
ORDER BY salary DESC
) AS salary_rank,
DENSE_RANK() OVER (
ORDER BY salary DESC
) AS dense_salary_rank
FROM employees;
Result:
| Employee | Salary | RANK | DENSE_RANK |
|---|---|---|---|
| Kumar | 60000 | 1 | 1 |
| Ravi | 60000 | 1 | 1 |
| Arun | 50000 | 3 | 2 |
| Divya | 45000 | 4 | 3 |
| Priya | 35000 | 5 | 4 |
Therefore, use RANK() when tied positions should create gaps. Use DENSE_RANK() when you want continuous ranking.
Example 3: How Does SUM() Calculate a Running Total?
A running total calculates the cumulative sum of values in a specified order.
SELECT
employee_name,
salary,
SUM(salary) OVER (
ORDER BY employee_id
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_total
FROM employees;
This query adds each employee’s salary to the previous total. Consequently, every row displays an updated cumulative amount.
Example 4: How Does AVG() Compare Department Salaries?
The AVG() window function calculates the average salary within each department.
SELECT
employee_name,
department,
salary,
AVG(salary) OVER (
PARTITION BY department
) AS department_average
FROM employees;
This query calculates separate averages for IT and HR. Moreover, it displays each employee’s salary alongside the corresponding department average.
Example 5: How Do LAG() and LEAD() Work?
LAG() retrieves a value from a previous row, whereas LEAD() retrieves a value from a following row.
SELECT
employee_name,
salary,
LAG(salary) OVER (
ORDER BY employee_id
) AS previous_salary,
LEAD(salary) OVER (
ORDER BY employee_id
) AS next_salary
FROM employees;
These functions help compare records without requiring a self-join.
For example, a sales analyst can use LAG() to compare this month’s revenue with the previous month’s revenue.
Example 6: How Can You Find the Top Two Employees in Each Department?
You can combine ROW_NUMBER() with a subquery to identify the highest-paid employees in every department.
SELECT *
FROM (
SELECT
employee_name,
department,
salary,
ROW_NUMBER() OVER (
PARTITION BY department
ORDER BY salary DESC, employee_id
) AS row_num
FROM employees
)
WHERE row_num <= 2;
First, SQL creates a separate ranking for each department. Next, the outer query selects the first two employees from each group.
This technique is useful for employee rankings, sales reports, and business performance analysis.
What Is the Difference Between GROUP BY and Window Functions?
Both techniques perform calculations across records. However, they produce different results.
| Feature | GROUP BY | Window Functions |
|---|---|---|
| Main purpose | Groups records | Calculates across related records |
| Individual rows | Usually combines rows | Retains individual rows |
| Ranking | Not directly supported | Supports ranking functions |
| Running totals | Requires additional query logic | Can calculate directly |
| Department averages | Produces grouped averages | Displays averages alongside individual records |
For example, GROUP BY can calculate the average salary for each department. Meanwhile, AVG() OVER (PARTITION BY department) displays that average for every employee.
Therefore, choose the method based on the output you need.
Where Are SQL Window Functions Used in Real Projects?
SQL window functions support several business and analytical activities.
Common applications include:
- Sales Analysis: Calculate running revenue and compare monthly performance.
- Employee Management: Rank employees based on salary or performance.
- Financial Reporting: Calculate cumulative balances and transaction comparisons.
- Customer Analytics: Identify repeat customers and compare purchase activity.
- E-Commerce: Rank products based on sales and identify top-performing categories.
- Business Intelligence: Prepare analytical datasets for Power BI and reporting dashboards.
For instance, an e-commerce company can use DENSE_RANK() to identify its best-selling products within each category. Similarly, LAG() can help compare monthly revenue.
Common Mistakes to Avoid When Using Window Functions
Beginners sometimes make mistakes when writing analytical queries. Understanding these issues helps you write more accurate SQL.
- Forgetting OVER(): Most window functions require the OVER() clause to define their calculation window.
- Confusing GROUP BY and PARTITION BY: GROUP BY combines records, whereas PARTITION BY creates calculation groups without removing individual rows.
- Ignoring Tied Values: Understand the differences between ROW_NUMBER(), RANK(), and DENSE_RANK().
- Using the Wrong Sorting Column: Choose a meaningful ORDER BY column to get reliable rankings.
- Ignoring Window Frames: Running totals and moving averages may produce unexpected results if you do not understand the frame definition.
- Filtering Too Early: Window functions are evaluated after WHERE, GROUP BY, and HAVING. Use a subquery or common table expression when filtering their calculated results.
How Can Beginners Learn SQL Window Functions?
Beginners should learn SQL window functions after understanding basic SQL queries and database concepts.
Follow this practical learning roadmap:
- Learn SELECT, WHERE, ORDER BY, and GROUP BY.
- Understand aggregate functions such as SUM(), AVG(), and COUNT().
- Practise the OVER() clause and PARTITION BY.
- Learn ranking functions and navigation functions.
- Practise running totals and moving averages.
- Complete employee, sales, and customer analysis projects.
- Practise interview questions using real datasets.
Furthermore, Oracle SQL is a useful database technology to explore during this learning journey. Understanding SQL fundamentals also prepares you to study advanced Oracle PL/SQL concepts.
Build Your Oracle SQL Skills with Infycle Technologies
Learning SQL becomes easier when you combine concepts with regular practical exercises.
Infycle Technologies helps students and job seekers develop database and programming skills through structured software training.
Our Oracle-related learning areas include:
- SQL fundamentals and query writing
- Oracle database concepts
- Joins, subqueries, and analytical functions
- PL/SQL fundamentals
- Practical database exercises
- Project-based learning and interview preparation
Whether you come from an Arts, Commerce, Science, or Engineering background, start by building your SQL fundamentals and progress towards advanced database concepts.
If you are exploring Oracle PLSQL training in Chennai, practical learning can help you understand how these technologies work in real business applications.
Frequently Asked Questions
1. What are SQL Window Functions?
SQL window functions perform calculations across related rows without combining them into one result. They support ranking, running totals, averages, and comparisons. For example, you can calculate department-wise salary rankings while displaying every employee’s original record.
2. What is the difference between RANK() and DENSE_RANK()?
Both functions assign the same rank to tied values. However, RANK() skips the next rank after a tie, whereas DENSE_RANK() continues without gaps. For example, tied first-place records receive ranks 1 and 1, followed by 3 with RANK() and 2 with DENSE_RANK().
3. Can we use GROUP BY and window functions together?
Yes, you can use GROUP BY and window functions in the same SQL query. SQL performs grouping before evaluating window functions. This approach helps analysts calculate rankings or percentages across grouped business results.
4. Are SQL Window Functions supported in Oracle?
Yes. Oracle Database supports analytic functions, which provide window-based calculations. Functions such as ROW_NUMBER(), RANK(), DENSE_RANK(), LAG(), LEAD(), and SUM() OVER() are useful for reporting and analytical queries.
5. Are SQL Window Functions useful for Data Analysts?
Yes. They help Data Analysts calculate rankings, running totals, moving averages, and changes between periods. Furthermore, these functions support sales reporting, customer analysis, financial reporting, and business intelligence projects.
Conclusion
SQL window functions make complex database analysis easier by allowing you to calculate values across related records while preserving individual rows.
Start with the OVER() clause, PARTITION BY, and ORDER BY. Then practise ranking functions, aggregate calculations, and navigation functions using real datasets.
As you gain confidence, explore advanced Oracle SQL and PL/SQL concepts to strengthen your database knowledge.
If you are looking for Oracle PLSQL training in Chennai, Infycle Technologies can help you build a foundation through structured learning and practical database exercises.





