For the term used in signal processing, see Window function.
In SQL, a window function or analytic function[1] is a function which uses values from one or multiple rows to return a value for each row. (This contrasts with an aggregate function, which returns a single value for multiple rows.) Window functions have an OVER clause; any function without an OVER clause is not a window function, but rather an aggregate or single-row (scalar) function.[2]
Example
As an example, here is a query which uses a window function to compare the salary of each employee with the average salary of their department (example from the PostgreSQL documentation):[3]
The PARTITION BY clause groups rows into partitions, and the function is applied to each partition separately. If the PARTITION BY clause is omitted (such as with an empty OVER() clause), then the entire result set is treated as a single partition.[4] For this query, the average salary reported would be the average taken over all rows.
Window functions are evaluated after aggregation (after the GROUP BY clause and non-window aggregate functions, for example).[1]
Syntax
According to the PostgreSQL documentation, a window function has the syntax of one of the following:[4]
frame_start and frame_end can be UNBOUNDED PRECEDING, offset PRECEDING, CURRENT ROW, offset FOLLOWING, or UNBOUNDED FOLLOWING. frame_exclusion can be EXCLUDE CURRENT ROW, EXCLUDE GROUP, EXCLUDE TIES, or EXCLUDE NO OTHERS.
expression refers to any expression that does not contain a call to a window function.
Notation:
Brackets [] indicate optional clauses
Curly braces {} indicate a set of different possible options, with each option delimited by a vertical bar |
Example
Window functions allow access to data in the records right before and after the current record.[5][6][7][8] A window function defines a frame or window of rows with a given length around the current row, and performs a calculation across the set of data in the window.[9][10]
NAME |
------------
Aaron| <-- Preceding (unbounded)
Andrew|
Amelia|
James|
Jill|
Johnny| <-- 1st preceding row
Michael| <-- Current row
Nick| <-- 1st following row
Ophelia|
Zach| <-- Following (unbounded)
In the above table, the next query extracts for each row the values of a window with one preceding and one following row: