SQL Window Functions
SQL Window Functions
Guide to SQL
Window
Functions
@saibysani18 Swipe
@saibysani18
1. Syntax Overview
Swipe
@saibysani18
Swipe
@saibysani18
2. Common
WindowFunctions
Swipe
@saibysani18
ROW_NUMBER()
Assigns a unique sequential integer to
rows within a partition, starting at 1 for
the first row in each partition.
Swipe
@saibysani18
RANK()
Ranks rows within a partition, with
gaps in the ranking for ties. If two
values are the same, they will
receive the same rank, and the next
rank will skip a number.
Swipe
@saibysani18
DENSE_RANK()
Similar to RANK(), but without gaps in the
ranking. Tied values will share the same
rank, and the next rank will continue
sequentially.
Swipe
@saibysani18
NTILE()
Divides the result set into a specified
number of buckets and assigns a bucket
number to each row.
Swipe
@saibysani18
LAG()
Provides access to a row at a specified
physical offset before the current row in the
result set.
This will return the salary from the previous
row for each employee.
Swipe
@saibysani18
LEAD()
Similar to LAG(), but it accesses the next
row's data.
Swipe
@saibysani18
3. Aggregate Functions
with
Window Functions
Swipe
@saibysani18
SUM()
Calculates the running total or sum of
values within a partition.
Swipe
@saibysani18
AVG()
Calculates the average of a set of values.
Swipe
@saibysani18
Swipe
@saibysani18
Swipe
@saibysani18
ROWS/RANGE
Specifies the window frame to which the function is
applied.
ROWS BETWEEN UNBOUNDED PRECEDING AND
CURRENT ROW: This window frame includes all rows
from the start of the partition up to the current row.
RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING:
This includes rows within a range of values relative to
the current row.
Swipe
@saibysani18
5. Performance
Considerations
Swipe
@saibysani18
Swipe
Loved this?