SQL reference

SQL window functions, explained simply

In Excel, you'd reach for
fxA formula that looks at other rows: running SUM, RANK, the row above

GROUP BY squashes rows into totals. A window function calculates across rows but keeps every row, so each row can show its own value and something about its neighbours: its rank, the running total so far, last month's number.

In Excel you'd drag formulas like =SUM($B$2:B2) or =B3-B2 down a column. Windows do that in one line. The OVER (…) part defines the "window": PARTITION BY restarts it for each group, ORDER BY sets the order to walk through.

Syntax

FUNCTION() OVER (
  PARTITION BY group_col  -- optional: restart per group
  ORDER BY sort_col       -- optional: order within it
)
Try itEdit the query, then Run
monthunitsrunning_totalchange_vs_last_monthbest_month_rank
2026-01313313empty2
2026-02289602-244
2026-0328989104
2026-043081199193
2026-053661565581
2026-062781843-886

6 rows

The ones you'll use most

  • SUM(x) OVER (ORDER BY d): running total
  • AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW): rolling average
  • LAG(x) / LEAD(x): the previous / next row's value, for period-over-period change
  • ROW_NUMBER(), RANK(), DENSE_RANK(): rankings, and top N per group
  • SUM(x) OVER (PARTITION BY g): the group total on every row, for "% of total"

Window functions work in Postgres, MySQL 8+, SQL Server, BigQuery, Snowflake and SQLite.

Your turn

Each product's share of total units sold: product_id, units, and pct_of_total (units ÷ all units × 100, rounded to 1 decimal).

This page on one card

SQL window functions, explained simply: the Excel way (A formula that looks at other rows: running SUM) and the SQL query, side by side
SQL window functions, explained simply, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows