Window Function is a SQL function that performs calculations on a group of rows while retaining the individual rows. GROUP BY aggregates into one row per group, but a window function preserves all rows and adds a calculated value to each row.
The window is defined through the OVER clause. PARTITION BY divides the rows into groups (optional), and ORDER BY specifies the sort order. In addition, ROWS or RANGE can be used to fine-tune the window frame (the range of rows included in the calculation).
Representative window functions include: ROW_NUMBER (sequential row number), RANK (ties get the same rank, the next rank is skipped), DENSE_RANK (ties get the same rank, the next rank is consecutive), LAG/LEAD (reference the previous/next row value), SUM/AVG/COUNT OVER (cumulative/moving aggregates), FIRST_VALUE/LAST_VALUE (first/last value), and others.
It is essential for analytical tasks such as ranking, running totals, moving averages, row-to-row comparisons, and ratio calculations, and it is also advantageous in terms of performance because complex calculations can be performed with a single table scan without a subquery.