Sitemap
Sanjay Singh

Sanjay Singh

Data Engineer | Power BI | Azure | Databricks | PySpark | SQL. Sharing practical Data Engineering, Analytics & Cloud tutorials

Window Function

3 min readAug 6, 2026

A Window Function performs calculations across a set of rows related to the current row without collapsing the result into a single row.

Get Sanjay Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

ROW_NUMBER :- Assign a unique number to every row.

Press enter or click to view image in full size
select *,
row_number() over(PARTITION BY department ORDER BY salary DESC)as row_num
from employee;
Press enter or click to view image in full size

RANK :- Assign the same rank to duplicate value.

SELECT *,
RANK() OVER(PARTITION BY department ORDER BY salary DESC) as rank
FROM employee;

DENSE_RANK() :- Work like rank but don’t skip number.

SELECT *,
DENSE_RANK() OVER(PARTITION BY department ORDER BY salary DESC) AS dens_rnk
FROM employee;

LAG :- Return the previous row value.

Press enter or click to view image in full size
SELECT MONTH,
sales,
LAG(sales) over(ORDER BY MONTH) as Previous_month_sales
FROM sales;
Press enter or click to view image in full size

LEAD() :- Return the next row value.

SELECT *,
LEAD(sales) over(ORDER BY MONTH) AS Next_month_sales
FROM sales;
Press enter or click to view image in full size

FIRST_VALUE() :- Return the first value in the window.

Press enter or click to view image in full size
SELECT *,
FIRST_VALUE(Amount) OVER(PARTITION BY Customer ORDER BY OrderDate) AS first_order_amt
FROM orders;
Press enter or click to view image in full size

LAST_VALUE() :- Return the last value in the window.

SELECT *,
LAST_VALUE(Amount) OVER(PARTITION BY Customer ORDER BY OrderDate
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS latest_order_amt
FROM orders;
Press enter or click to view image in full size

NTILE() :- Divide rows into equal groups.

Press enter or click to view image in full size
SELECT *,
NTILE(4) OVER(ORDER BY Marks DESC)AS Quartile
FROM Student;
Press enter or click to view image in full size

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Data Engineer | Power BI | Azure | Databricks | PySpark | SQL. Sharing practical Data Engineering, Analytics & Cloud tutorials