Master SQL Window Functions: From Basic Queries to Advanced Data Analytics
SQL SCHOOL | TECH & CAREERS
Technical Tutorial Series – Edition 01
Introduction
Have you ever been asked to find the top three employees in each department, calculate running sales totals or compare current-month revenue with previous-month revenue?
These are common requirements in real-world Data Engineering, Business Intelligence and Data Analytics projects.
SQL Window Functions provide a powerful way to solve these requirements while retaining individual records.
- What are SQL Window Functions?
A Window Function performs a calculation across a set of rows related to the current row without collapsing those rows into a single result.
Unlike GROUP BY, Window Functions allow us to retain individual records while performing analytical calculations.
- GROUP BY vs Window Functions
GROUP BY combines multiple rows into summary records.
Window Functions retain individual records and add analytical information to each row.
For example, GROUP BY can return the total salary of each department, whereas a Window Function can display each employee's salary alongside the department's total salary.
- General Syntax
FUNCTION_NAME(expression)
OVER (
PARTITION BY column_name
ORDER BY column_name
)
OVER defines the window.
PARTITION BY divides records into logical groups.
ORDER BY defines the calculation sequence.
ROWS or RANGE can define the window frame for supported functions.
- Important SQL Window Functions
ROW_NUMBER()
Assigns a unique sequential number to each row within a partition.
SELECT EmployeeName, Department, Salary,
ROW_NUMBER() OVER (
PARTITION BY Department
ORDER BY Salary DESC, EmployeeName
) AS RowNum
FROM Employees;
Use case: Selecting the latest record or removing duplicate records.
RANK()
Assigns the same rank to tied values and skips subsequent rank numbers.
SELECT EmployeeName, Salary,
RANK() OVER (
ORDER BY Salary DESC
) AS SalaryRank
FROM Employees;
Use case: Employee performance ranking.
DENSE_RANK()
Assigns equal ranks to tied values without skipping subsequent rank numbers.
SELECT EmployeeName, Salary,
DENSE_RANK() OVER (
ORDER BY Salary DESC
) AS SalaryRank
FROM Employees;
Use case: Finding the second or third highest distinct salary.
SUM() OVER()
Calculates aggregate values while retaining individual rows.
SELECT EmployeeName, Department, Salary,
SUM(Salary) OVER (
PARTITION BY Department
) AS DepartmentTotal
FROM Employees;
Use case: Comparing individual salary with department expenditure.
LAG()
Retrieves a value from a previous row.
SELECT SalesMonth, Revenue,
LAG(Revenue) OVER (
ORDER BY SalesMonth
) AS PreviousRevenue
FROM MonthlySales;
Use case: Month-over-month revenue comparison.
LEAD()
Retrieves a value from a subsequent row.
SELECT SalesMonth, Revenue,
LEAD(Revenue) OVER (
ORDER BY SalesMonth
) AS NextRevenue
FROM MonthlySales;
Use case: Comparing a record with its following record.
- Real-Time Project Scenario: E-Commerce Sales Analytics
Imagine you are working as a Data Engineer for an e-commerce organization.
The business requires:
Top-performing products by category.
Monthly revenue comparisons.
Cumulative sales totals.
Customer purchase rankings.
Latest transactions for each customer.
Window Functions can help calculate these analytical metrics before the data is consumed by reporting tools such as Power BI.
Calculate running monthly revenue
SELECT SalesMonth, Revenue,
SUM(Revenue) OVER (
ORDER BY SalesMonth
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS RunningRevenue
FROM MonthlySales;
Assume MonthlySales contains one record per month.
Find the top three distinct salary levels in each department
WITH RankedEmployees AS (
SELECT EmployeeName, Department, Salary,
DENSE_RANK() OVER (
PARTITION BY Department
ORDER BY Salary DESC
) AS SalaryRank
FROM Employees
)
SELECT *
FROM RankedEmployees
WHERE SalaryRank <= 3;
This query includes employees tied at any of the top three distinct salary levels.
- SQL Window Function Best Practices
Use meaningful PARTITION BY columns.
Use deterministic ordering when assigning unique row numbers.
Specify window frames explicitly when calculating running totals.
Avoid unnecessary sorting operations.
Analyze execution plans for large datasets.
Evaluate suitable indexes based on the query workload.
Use CTEs for readable analytical queries.
- Interview Questions
What is the difference between GROUP BY and Window Functions?
How do ROW_NUMBER(), RANK() and DENSE_RANK() differ?
How do you find the top three salaries in each department?
What is the difference between LAG() and LEAD()?
How do you calculate a running total using SQL?
- Hands-On Practice Assignment
Create an employee or sales dataset and write SQL queries to:
Find the second highest distinct salary.
Rank employees within each department.
Calculate cumulative sales.
Compare monthly revenue with previous-month revenue.
Identify the latest transaction for each customer.
- Key Takeaway
SQL Window Functions are valuable analytical skills for modern SQL Developers, Data Analysts and Data Engineers.
These concepts are applicable across Microsoft SQL Server, PostgreSQL, Snowflake, Databricks SQL and other modern data platforms, although syntax and supported features may differ.
Don't just memorize SQL syntax. Understand how to solve actual business requirements using SQL.
Upgrade Your Technical Skills with SQL SCHOOL
Explore professional hands-on training, real-time projects, certification guidance and career support.
Microsoft SQL Server & T-SQL Training:
https://sqlschool.com/microsoft-sql-training/
Explore Professional IT Courses:
https://sqlschool.com/
Attend FREE Technical Demos:
https://demo.sqlschool.com/
Explore IT Job Opportunities:
https://jobs.sqlschool.com/
Career & Training Guidance:
https://wa.me/919951440801
Join Our Official WhatsApp Channel:
https://whatsapp.com/channel/0029VamSJLI35fLmVEvCPD3r
Contact: +91 99514 40801
Follow SQL SCHOOL for regular SQL, Python, Data Engineering and AI tutorials.
SQL SCHOOL – Expert Training. Career Success.
Top comments (0)