Sarth Calhoun

SQL · Message

Window functions, the mental model

Adapted from a piece I wrote in July 2024, about work I did starting in the fall of 2022.

In addition to the official Postgres docs for window functions, there are some examples in the Snowflake documentation that might help you have an "aha!" moment. I find that the easiest way to grok window functions is to first compare them to aggregate functions such as SUM() or COUNT(). Where SUM or COUNT will return a single row, or a row for each GROUP BY, the window function will return all the rows, but they can contain a column with a value that is the result of calculations performed across some or all of the rows (within a partition, which again, is just a subset of rows). Here are a couple of things worth clearing up: