WINDOW clause
The WINDOW clause defines named windows. A window function refers to one with OVER window_name. It can also start from a named window that has no ORDER BY of its own and add one, as in OVER (w ORDER BY amount DESC).
A window definition can have PARTITION BY, which splits the rows into groups that are computed separately, and ORDER BY, which orders the rows in each partition. It can also have a frame, such as ROWS BETWEEN 1 PRECEDING AND CURRENT ROW, which limits the rows that each calculation sees.
Syntax
WINDOW window_name AS ( [ existing_window_name ]
[ PARTITION BY expression [, ...] ]
[ ORDER BY expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] [ frame ] ) [, ...]
frame: { ROWS | RANGE
| GROUPS } BETWEEN frame_start AND frame_end
Examples
For a description of the sample tables that the examples on this page use, see SELECT statement in DuckDB.
The following SQL query defines the window w once, uses it for a regional total, and extends it with ORDER BY to rank the orders in each region.
SELECT order_id, region, amount, sum(amount) OVER w AS region_total, rank() OVER ( w ORDER BY amount DESC NULLS LAST ) AS rank_in_region FROM sales_db.sales_parquet WINDOW w AS (PARTITION BY region) ORDER BY region, rank_in_region
The query returns the following results.
| order_id | region | amount | region_total | rank_in_region |
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query uses a frame to add each order's amount to the amount of the order before it. For the last order, whose amount is NULL, sum skips the NULL value.
SELECT order_id, amount, sum(amount) OVER w AS two_order_total FROM sales_db.sales_parquet WINDOW w AS ( ORDER BY order_id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW ) ORDER BY order_id
The query returns the following results.
| order_id | amount | two_order_total |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|