What are Window Functions?
Window Functions allow you to perform calculations across a set of table rows that are somehow related to the current row. Unlike regular aggregate functions (
SUM, AVG), window functions do NOT group rows into a single output row; the rows retain their individual identities.The keyword for window functions is
OVER.1. Syntax
sql
2. Ranking Functions
These are used to assign a rank or row number to each row within a partition.
ROW_NUMBER(): Unique incrementing number.RANK(): Assigns the same rank to ties (skips the next number).DENSE_RANK(): Assigns the same rank to ties (doesn't skip).
sql
3. Aggregate Window Functions
You can calculate running totals, averages, or moving averages without a
GROUP BY.sql
4. Value Functions
These allow you to access data from other rows relative to the current row.
LAG(col, n): Get value fromnrows before.LEAD(col, n): Get value fromnrows after.
sql
5. Frames (ROWS BETWEEN)
You can further restrict the "window" of rows used for the calculation using a frame clause.
sql
Summary Checklist
- Window functions use the
OVERclause. - Rows are NOT collapsed (unlike
GROUP BY). - Use
PARTITION BYto group calculations. - Use
ORDER BYto define sequences (like running totals). -
LAG/LEADare essential for time-series analysis. -
RANKis perfect for "Top N" queries within categories.