Guide to Window Functions
Window functions partition a table before they run, making them very useful when working with large datasets
Last updated
Window functions partition a table before they run, making them very useful when working with large datasets
Last updated
Window functions enable users to perform calculations against partitions (i.e. subgroups or sections) of a table. Unlike traditional aggregation functions, window functions partition the table behind the scenes and perform calculations against each partition instead of the entire table.
Let's say that we have a list of populations for each state, broken out by region. If we use SUM
to add up the population, we'd get the total for the whole column:
But what if we wanted to sum the population for each region? In that case, we'd want my new column to contain the total for region each state is in. For that, instead of using SUM
, we'd use the alternative window function SUMBY
:
Here, we still add up our Adult Population
but we segment by Region
. So for each state, we list its region's total population.
Many functions are accompanied by their window function equivalents, which perform the same function but on partitioned tables. Generally, window functions take one additional argument, the column on which to partition. Window functions available:
Function
Description
Rank values within a group
Total values within a group
Find adjacent values within a group
Count the non-null values within a group