Window Function
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.
select *,
row_number() over(PARTITION BY department ORDER BY salary DESC)as row_num
from employee;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.
SELECT MONTH,
sales,
LAG(sales) over(ORDER BY MONTH) as Previous_month_sales
FROM sales;LEAD() :- Return the next row value.
SELECT *,
LEAD(sales) over(ORDER BY MONTH) AS Next_month_sales
FROM sales;FIRST_VALUE() :- Return the first value in the window.
SELECT *,
FIRST_VALUE(Amount) OVER(PARTITION BY Customer ORDER BY OrderDate) AS first_order_amt
FROM orders;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;NTILE() :- Divide rows into equal groups.
SELECT *,
NTILE(4) OVER(ORDER BY Marks DESC)AS Quartile
FROM Student;





