tech

SQL Window Functions

sqldatabaseanalytics

Window functions perform calculations across a set of rows related to the current row without collapsing them.

The Syntax

SELECT
  name,
  salary,
  AVG(salary) OVER (PARTITION BY department) AS dept_avg
FROM employees;

Common Functions

  • ROW_NUMBER(), RANK(), DENSE_RANK() — ordering
  • LAG(), LEAD() — access previous/next rows
  • SUM() OVER (ORDER BY date) — running totals

Once you learn window functions, you will wonder how you lived without them.