A window function is a type of SQL operation that aggregates over a partition of the result set.
As a basic example of a window function, consider a table that contains a list persons along with their age and gender.
If you wanted a query to return the complete list of people along with their age rank per gender, you could accomplish this most simply by using a ranking window function.
Such a function can be used to rank individual rows within a subset of the results.
Using a window function the above function would look like this:
SELECT name,
age,
gender,
RANK() OVER (PARTITION BY gender ORDER BY age DESC) AS age_rank
FROM persons
Window functions as defined by the SQL standard can also access rows before and after the current row using the lag()
or lead()
function. The following query calculates the delta to the previous row for the amount column for each customer:
SELECT customer_id,
order_date,
amount,
amount - lag(amount) over (partition by customer_id ORDER BY order_date) as delta
FROM order
ORDER BY customer_id, order_date;
Standard aggregates (e.g. count()
, sum()
) can also be used as a window function. If combined with an ORDER BY
(inside the partition defintion) this will generate "running" totals based on the aggregate being used.
Window functions are available in a wide range of DBMS: Oracle (called "analytical functions" there), Microsoft SQL Server, DB2 (called "olap functions" there) PostgreSQL, Teradata, Sybase, Vertica, and partially in H2 Database.