Window functions in DuckDB
Use window functions to compute a value for each row from a set of related rows. For example, you can compute a row number, a rank, a running total, or the value from the previous row. Unlike an aggregate function with GROUP BY, a window function does not combine rows. The query returns one row for each input row, and the window function adds a value to each one. A window function call always ends with an OVER clause. The OVER clause defines the window, which is the set of rows that the function reads for each row. For more information about the OVER clause, see OVER clause.
PARTITION BY in the OVER clause splits the rows into partitions, and the function is computed separately for each partition. As a result, a row number or a rank starts again at 1 in each one. Without PARTITION BY, all the rows of the query form one partition. ORDER BY in the OVER clause sets the order of the rows in each partition. Rows that have the same ORDER BY values are called peers. The ranking functions (row_number, rank, dense_rank, percent_rank, and cume_dist) and lag, lead, ntile, and fill depend on that order, so give them an ORDER BY. Without it, the order of the rows in a partition is not defined, and rank, dense_rank, percent_rank, and cume_dist treat all the rows of the partition as peers. By default, NULL values sort last, for both ASC and DESC. The ORDER BY in the OVER clause does not sort the query result. When you need the rows in a particular order, add an ORDER BY clause to the query.
A frame limits the rows of the partition that an aggregate function, first_value, last_value, or nth_value reads for the current row. A ROWS frame counts rows, and a GROUPS frame counts groups of peers. A RANGE frame selects the rows whose ORDER BY value is within a distance of the current row's value. For example, ROWS BETWEEN 2 PRECEDING AND CURRENT ROW reads the current row and the two rows before it. With ORDER BY on a DATE column, RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW reads the rows from the current row's date and the six days before it. When the window has an ORDER BY and no frame, the frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. This frame runs from the start of the partition through the current row and its peers, so sum returns a running total. When the window has no ORDER BY, the frame is the whole partition. The ranking functions and lag, lead, ntile, and fill ignore the frame.
By default, first_value, last_value, nth_value, lag, and lead read NULL values like any other value. To state this default in a query, write RESPECT NULLS. To skip the rows where the value is NULL, write IGNORE NULLS inside the parentheses, after the last argument, as in lag(amount IGNORE NULLS) or lag(amount, 2, 0 IGNORE NULLS). Unlike Athena engine version 3, DuckDB does not accept IGNORE NULLS after the closing parenthesis. The aggregate functions first and last also accept IGNORE NULLS when you use them with OVER, and then they skip the NULL values. The other aggregate functions, the ranking functions, and fill do not accept IGNORE NULLS.
You can use any aggregate function as a window function by adding an OVER clause, as in sum(amount) OVER (PARTITION BY region). DISTINCT and ORDER BY inside the parentheses, and FILTER after them, work as they do in a grouped query. For more information about aggregate functions, see Aggregate functions in DuckDB.
A query computes its window functions after WHERE, GROUP BY, and HAVING. In a grouped query, a window function reads the groups, and its arguments, PARTITION BY, and ORDER BY can use aggregate functions, as in rank() OVER (ORDER BY sum(amount) DESC). You can use window functions in the select list, in ORDER BY, and in QUALIFY. You cannot use them in WHERE, and you cannot nest one window function call inside another. To filter rows on the result of a window function, use QUALIFY. To share one window definition among several calls, name it in the WINDOW clause and write OVER . For more information about these clauses, see QUALIFY clause and WINDOW clause.window_name
The following table lists the window functions that this topic describes.
| Function | Description |
|---|---|
Returns the fraction of the rows in the partition that sort before the current row or tie with it. |
|
Returns a rank for each row in its partition, where tied rows share a rank and the next rank is one higher, so no rank numbers are skipped. |
|
Estimates each |
|
Returns the value of an expression at the first row of the window frame. |
|
Returns a value from an earlier row of the partition, a set number of rows back from the current row. |
|
Returns the value of an expression at the last row of the window frame. |
|
Returns a value from a later row of the partition, a set number of rows ahead of the current row. |
|
Returns the value of an expression at a given position in the window frame. |
|
Divides the rows of each partition into a number of buckets and returns the bucket number of the current row. |
|
Defines the partitions, the row order, and the frame that a window function reads. |
|
Returns the current row's rank in its partition, scaled to a value from |
|
Returns a rank for each row in its partition, where tied rows share a rank and the next rank skips the numbers that the ties used up. |
|
rank_dense |
Alias of dense_rank. |
Returns the position of the current row in its partition, where the first row is |
cume_dist function
Counts the rows of the partition from the first row through the current row and the rows that tie with it on the ORDER BY values, called peers. It returns that count as a fraction of all the rows in the partition. The result is greater than 0 and at most 1. Peers get the same value, and that value counts all of them, so the last peer group of each partition gets 1.
To get a relative rank that starts at 0 for the first row, use the percent_rank function.
Syntax
cume_dist() OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] )
Arguments
The cume_dist function takes the following arguments:
partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the function is computed separately for each partition. This argument is optional. sort_expression-
An expression that sets the order of the rows in each partition. It can be of any data type that can be sorted. Rows that have the same values for every
sort_expressionare peers. This argument is optional.
Return type
DOUBLE
Examples
The following SQL query returns, for each athlete, the fraction of athletes who scored the same number of points or more. The athletes ben and cai tie, so for both of them the function counts three of the five rows and returns 0.6.
SELECT athlete, points, cume_dist() OVER ( ORDER BY points DESC ) AS cumulative_share FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 85), ('dev', 70), ('eli', 60) ) AS results(athlete, points) ORDER BY points DESC, athlete
The query returns the following results.
| athlete | points | cumulative_share |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query shows where a NULL amount falls. NULL values sort last by default, so the row with the NULL amount gets 1.0.
SELECT amount, cume_dist() OVER ( ORDER BY amount ) AS cumulative_share FROM (VALUES (10), (NULL), (20), (30)) AS orders(amount) ORDER BY amount
The query returns the following results.
| amount | cumulative_share |
|---|---|
|
|
|
|
|
|
|
|
Considerations
Without ORDER BY in the window, all the rows of a partition are peers, so every row gets 1.
NULL values of sort_expression are peers of each other and, by default, sort after all other values, so they form the last peer group and get 1. To sort them first, add NULLS FIRST to the window's ORDER BY.
dense_rank function
Returns the rank of the current row in its partition, in the order that the window's ORDER BY sets. Rows that tie on the ORDER BY values, called peers, get the same rank. The next set of values gets the next number, so the ranks have no gaps. For example, if two rows tie for rank 2, the next row has rank 3. The result equals the number of distinct ORDER BY values from the start of the partition through the current row.
rank_dense is an alias of dense_rank. To skip the ranks that tied rows use up, use the rank function.
Syntax
dense_rank() OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] )
Arguments
The dense_rank function takes the following arguments:
partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the ranks start again at 1 in each partition. This argument is optional. sort_expression-
An expression that sets the order in which the rows are ranked. It can be of any data type that can be sorted. Rows that have the same values for every
sort_expressionget the same rank. This argument is optional.
Return type
BIGINT
Examples
The following SQL query compares dense_rank with rank. ben and cai tie for rank 2. The next athlete gets rank 3 from dense_rank and rank 4 from rank.
SELECT athlete, points, dense_rank() OVER ( ORDER BY points DESC ) AS dense_rank_value, rank() OVER (ORDER BY points DESC) AS rank_value FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 85), ('dev', 70), ('eli', 60) ) AS results(athlete, points) ORDER BY points DESC, athlete
The query returns the following results.
| athlete | points | dense_rank_value | rank_value |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query uses the rank_dense alias with QUALIFY to keep the athletes who have one of the two highest point values in their event. The query keeps both relay athletes who have 85 points.
SELECT event, athlete, points FROM (VALUES ('relay', 'ana', 90), ('relay', 'ben', 85), ('relay', 'cai', 85), ('relay', 'dev', 70), ('relay', 'eli', 60), ('sprint', 'fay', 95), ('sprint', 'gus', 80) ) AS results(event, athlete, points) QUALIFY rank_dense() OVER ( PARTITION BY event ORDER BY points DESC ) <= 2 ORDER BY event, points DESC, athlete
The query returns the following results.
| event | athlete | points |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
Without ORDER BY in the window, all the rows of a partition are peers, so every row has rank 1.
NULL values of sort_expression tie with each other and, by default, sort after all other values, so they share the last rank.
fill function
Returns expression unchanged where it is not NULL. Where it is NULL, the function returns a value on the straight line between the nearest earlier and later rows of the partition that have a value. It uses the window's ORDER BY value as the position of each row. The result depends on the distance between the ORDER BY values, not on the number of rows between them. For example, with a value of 100 on 2026-10-01 and 400 on 2026-10-05, a NULL on 2026-10-02 becomes 175.
Before the first value or after the last value of a partition, fill extends the line through the two nearest values. If a partition has only one value that is not NULL, every NULL in that partition gets that value.
Syntax
fill(expression) OVER (
[ PARTITION BY partition_expression
[, ...] ] ORDER BY sort_expression [ ASC | DESC ]
[ NULLS { FIRST | LAST } ] )
Arguments
The fill function takes the following arguments:
expression-
The value to fill in. It must have a type that supports subtraction, such as
INTEGER,DOUBLE,DECIMAL,DATE, orTIMESTAMP. partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, andfillreads values only from the current row's partition. This argument is optional. sort_expression-
The expression that gives the position of each row on the line, of a type that supports subtraction, such as a number, a
DATE, or aTIMESTAMP. The window'sORDER BYmust have exactly onesort_expression.
Return type
The same type as expression, such as DECIMAL for a DECIMAL expression or DATE for a DATE expression.
Examples
The following SQL query fills in the missing value of row 2 halfway between the values of rows 1 and 3.
SELECT t, v, fill(v) OVER (ORDER BY t) AS result FROM (VALUES (1, 1.0), (2, NULL), (3, 3.0)) AS x(t, v) ORDER BY t
The query returns the following results.
| t | v | result |
|---|---|---|
|
|
|
|
|
|
|
|
|
The following SQL query fills in a missing amount by date. The date 2026-10-02 is one quarter of the way from 2026-10-01 to 2026-10-05, so its amount, 175.0, is one quarter of the way from 100.0 to 400.0.
SELECT day, amount, fill(amount) OVER (ORDER BY day) AS filled_amount FROM (VALUES (DATE '2026-10-01', 100.0), (DATE '2026-10-02', NULL), (DATE '2026-10-05', 400.0) ) AS daily(day, amount) ORDER BY day
The query returns the following results.
| day | amount | filled_amount |
|---|---|---|
|
|
|
|
|
|
|
|
|
The following SQL query fills two partitions. In sensor a, fill extends the line through the two nearest readings to fill in the first and last readings. Sensor b has only one value, so its NULL gets that value.
SELECT sensor, reading_time, reading, fill(reading) OVER ( PARTITION BY sensor ORDER BY reading_time ) AS filled_reading FROM (VALUES ('a', 1, NULL), ('a', 2, 20), ('a', 3, NULL), ('a', 4, 40), ('a', 5, NULL), ('b', 1, 7), ('b', 2, NULL) ) AS readings(sensor, reading_time, reading) ORDER BY sensor, reading_time
The query returns the following results.
| sensor | reading_time | reading | filled_reading |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query shows that fill truncates the value that it computes for an integer column, so the point halfway between 10 and 13 becomes 11. After a cast to DOUBLE, the result keeps the fraction and is 11.5.
SELECT t, v, fill(v) OVER (ORDER BY t) AS integer_fill, fill( CAST(v AS DOUBLE) ) OVER (ORDER BY t) AS double_fill FROM (VALUES (1, 10), (2, NULL), (3, 13)) AS x(t, v) ORDER BY t
The query returns the following results.
| t | v | integer_fill | double_fill |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
The window must have exactly one ORDER BY expression. A window with no ORDER BY, or with more than one expression in it, makes the query fail. A sort_expression or an expression of type VARCHAR also makes the query fail.
When expression has an integer type, the interpolated value is truncated to an integer, so a point halfway between 10 and 13 becomes 11. To keep the fraction, cast expression to DOUBLE or DECIMAL, as in fill(CAST(.expression AS DOUBLE))
fill does not accept IGNORE NULLS or RESPECT NULLS, and it ignores the window frame. A row whose sort_expression is NULL keeps its NULL value.
first_value function
Returns the value that expression has on the row where the window frame starts. With the default frame, that is the first row of the partition in the order that the window's ORDER BY sets. As a result, every row of a partition gets the same value. With a frame that starts later, such as ROWS BETWEEN 1 PRECEDING AND CURRENT ROW, it is the first row of that frame.
With IGNORE NULLS, the function returns the first value in the frame that is not NULL, or NULL if every value in the frame is NULL. To read the last row of the frame, use the last_value function. To read the row at a given position, use the nth_value function.
Syntax
first_value(expression
[ IGNORE NULLS | RESPECT NULLS ]) OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] [ frame ] )
Arguments
The first_value function takes the following arguments:
expression-
The value to return, of any data type.
partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the function reads only the current row's partition. This argument is optional. sort_expression-
An expression that sets the order of the rows in each partition, and so which row is first. It can be of any data type that can be sorted. This argument is optional.
frame-
A frame that limits the rows that the function reads, such as
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW. For more information about frames, see OVER clause. This argument is optional.
Return type
The same type as expression, such as VARCHAR for a VARCHAR expression.
Examples
The following SQL query returns the leader of each event, the athlete with the most points, on every row of that event.
SELECT event, athlete, points, first_value(athlete) OVER ( PARTITION BY event ORDER BY points DESC ) AS leader FROM (VALUES ('relay', 'ana', 90), ('relay', 'ben', 85), ('relay', 'cai', 80), ('relay', 'dev', 70), ('sprint', 'fay', 95), ('sprint', 'gus', 80) ) AS results(event, athlete, points) ORDER BY event, points DESC
The query returns the following results.
| event | athlete | points | leader |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query compares first_value with and without IGNORE NULLS. The first reading is NULL, so without IGNORE NULLS every row gets NULL. With IGNORE NULLS, row 1 gets NULL because its default frame has no value yet, and the later rows get 20, the first value that is not NULL.
SELECT reading_id, temperature, first_value( temperature ) OVER (ORDER BY reading_id) AS first_reading, first_value( temperature IGNORE NULLS ) OVER (ORDER BY reading_id) AS first_known_reading FROM (VALUES (1, NULL), (2, 20), (3, NULL), (4, 40) ) AS readings(reading_id, temperature) ORDER BY reading_id
The query returns the following results.
| reading_id | temperature | first_reading | first_known_reading |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
If several rows tie on the ORDER BY values at the start of the frame, the query does not define which of them is first. Add columns to ORDER BY until each row's values are unique.
Differences from Athena engine version 3
In Athena engine version 3, you write IGNORE NULLS after the closing parenthesis, as in first_value(. DuckDB rejects that form with a syntax error. Write expression) IGNORE NULLS OVER (ORDER BY sort_expression)IGNORE NULLS inside the parentheses instead, as in first_value(.expression IGNORE NULLS) OVER (ORDER BY sort_expression)
lag function
Counts back offset rows from the current row in its partition, in the order that the window's ORDER BY sets, and returns the value of expression on that row. With the default offset of 1, it returns the value from the previous row. When the count goes past the start of the partition, the function returns default, or NULL if you omit default.
Use lag to compare each row with an earlier one, for example to compute the change from the previous order. With IGNORE NULLS, the function counts back over only the rows where expression is not NULL. To read a later row, use the lead function.
Syntax
lag(expression [, offset [, default ] ]
[ IGNORE NULLS | RESPECT NULLS ]) OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] )
Arguments
The lag function takes the following arguments:
expression-
The value to return, of any data type.
offset-
The number of rows to count back from the current row, as a
BIGINT. The default is1. An offset of0returns the current row's value, and a negative offset counts forward, asleaddoes. IfoffsetisNULL, the result isNULL, even when you give adefault. This argument is optional. default-
The value to return when the row that
offsetpoints to is outside the partition. It is converted to the type ofexpression. If you omitdefault, the function returnsNULLwhen the row is outside the partition. This argument is optional. partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the function never reads a row from another partition. This argument is optional. sort_expression-
An expression that sets the order of the rows in each partition, and so which row is the previous one. It can be of any data type that can be sorted. This argument is optional.
Return type
The same type as expression, such as DECIMAL(5,2) for a DECIMAL(5,2) expression.
Examples
The following SQL query returns the amount of the previous order and the change from it. The first order has no previous order, so both values are NULL, and the change for order 6 is NULL because its amount is NULL.
SELECT order_id, amount, lag(amount) OVER ( ORDER BY order_id ) AS previous_amount, amount - lag(amount) OVER ( ORDER BY order_id ) AS change FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) ORDER BY order_id
The query returns the following results.
| order_id | amount | previous_amount | change |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query returns the amount of the previous order in the same region, with 0 as the default for the first order of each region.
SELECT region, order_id, amount, lag( amount, 1, 0 ) OVER (PARTITION BY region ORDER BY order_id) AS previous_in_region FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) ORDER BY region, order_id
The query returns the following results.
| region | order_id | amount | previous_in_region |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query compares lag with and without IGNORE NULLS. Without it, a row after a NULL reading gets NULL. With it, the function skips the NULL readings and returns the most recent reading before the current row that has a value.
SELECT reading_id, temperature, lag( temperature ) OVER (ORDER BY reading_id) AS previous_reading, lag( temperature IGNORE NULLS ) OVER (ORDER BY reading_id) AS previous_known_reading FROM (VALUES (1, 10), (2, NULL), (3, 30), (4, NULL), (5, 50) ) AS readings(reading_id, temperature) ORDER BY reading_id
The query returns the following results.
| reading_id | temperature | previous_reading | previous_known_reading |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query passes an offset and a default together with IGNORE NULLS, which goes after the last argument. Each row gets the second-most-recent reading before it that has a value, or 0 when there is none.
SELECT reading_id, temperature, lag( temperature, 2, 0 IGNORE NULLS ) OVER (ORDER BY reading_id) AS two_known_readings_back FROM (VALUES (1, 10), (2, NULL), (3, 30), (4, NULL), (5, 50) ) AS readings(reading_id, temperature) ORDER BY reading_id
The query returns the following results.
| reading_id | temperature | two_known_readings_back |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
default is converted to the type of expression. For an INTEGER expression, a default of 1.5 becomes 2, and a default of 'none' makes the query fail. To return a value of another type, cast expression first, as in lag(CAST(.expression AS VARCHAR), 1, 'none')
Without ORDER BY in the window, the query does not define which row is the previous one. If rows tie on the ORDER BY values, their order is not defined either, so add columns to ORDER BY until each row's values are unique.
Differences from Athena engine version 3
In Athena engine version 3, you write IGNORE NULLS after the closing parenthesis, as in lag(. DuckDB rejects that form with a syntax error. Write expression) IGNORE NULLS OVER (ORDER BY sort_expression)IGNORE NULLS inside the parentheses, after the last argument, as in lag( or expression IGNORE NULLS) OVER (ORDER BY sort_expression)lag(. For more information about differences that make a query fail, see Differences that make a query fail.expression, 2, 0 IGNORE NULLS) OVER (ORDER BY sort_expression)
last_value function
Returns the value that expression has on the row where the window frame ends. When the window has an ORDER BY and no frame, the frame ends at the current row and its peers. As a result, the function returns the value of the current row, or of the last of the rows that tie with it. It does not return the value of the last row of the partition. To get the last row of the partition, give the window the frame ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
With IGNORE NULLS, the function returns the last value in the frame that is not NULL. With the default frame, last_value( carries the most recent value forward over the expression IGNORE NULLS)NULL values that follow it. To read the first row of the frame, use the first_value function.
Syntax
last_value(expression
[ IGNORE NULLS | RESPECT NULLS ]) OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] [ frame ] )
Arguments
The last_value function takes the following arguments:
expression-
The value to return, of any data type.
partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the function reads only the current row's partition. This argument is optional. sort_expression-
An expression that sets the order of the rows in each partition, and so which row is last. It can be of any data type that can be sorted. This argument is optional.
frame-
A frame that limits the rows that the function reads, such as
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. For more information about frames, see OVER clause. This argument is optional.
Return type
The same type as expression, such as VARCHAR for a VARCHAR expression.
Examples
The following SQL query shows the effect of the frame. With the default frame, last_value returns the current row's athlete. With a frame that covers the whole partition, it returns the athlete with the fewest points on every row.
SELECT athlete, points, last_value(athlete) OVER ( ORDER BY points DESC ) AS last_in_default_frame, last_value(athlete) OVER (ORDER BY points DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_in_partition FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 80), ('dev', 70) ) AS results(athlete, points) ORDER BY points DESC
The query returns the following results.
| athlete | points | last_in_default_frame | last_in_partition |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query uses IGNORE NULLS with the default frame to carry the most recent reading forward over the missing readings.
SELECT reading_id, temperature, last_value( temperature IGNORE NULLS ) OVER (ORDER BY reading_id) AS latest_known_reading FROM (VALUES (1, 10), (2, NULL), (3, NULL), (4, 40), (5, NULL) ) AS readings(reading_id, temperature) ORDER BY reading_id
The query returns the following results.
| reading_id | temperature | latest_known_reading |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
If several rows tie on the ORDER BY values at the end of the frame, the query does not define which of them is last. Add columns to ORDER BY until each row's values are unique.
Differences from Athena engine version 3
In Athena engine version 3, you write IGNORE NULLS after the closing parenthesis, as in last_value(. DuckDB rejects that form with a syntax error. Write expression) IGNORE NULLS OVER (ORDER BY sort_expression)IGNORE NULLS inside the parentheses instead, as in last_value(.expression IGNORE NULLS) OVER (ORDER BY sort_expression)
lead function
Counts forward offset rows from the current row in its partition, in the order that the window's ORDER BY sets, and returns the value of expression on that row. With the default offset of 1, it returns the value from the next row. When the count goes past the end of the partition, the function returns default, or NULL if you omit default.
Use lead to compare each row with a later one, for example to find the next order of the same customer. With IGNORE NULLS, the function counts forward over only the rows where expression is not NULL. To read an earlier row, use the lag function.
Syntax
lead(expression [, offset [, default ] ]
[ IGNORE NULLS | RESPECT NULLS ]) OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] )
Arguments
The lead function takes the following arguments:
expression-
The value to return, of any data type.
offset-
The number of rows to count forward from the current row, as a
BIGINT. The default is1. An offset of0returns the current row's value, and a negative offset counts back, aslagdoes. IfoffsetisNULL, the result isNULL. This argument is optional. default-
The value to return when the row that
offsetpoints to is outside the partition. It is converted to the type ofexpression. If you omitdefault, the function returnsNULLwhen the row is outside the partition. This argument is optional. partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the function never reads a row from another partition. This argument is optional. sort_expression-
An expression that sets the order of the rows in each partition, and so which row is the next one. It can be of any data type that can be sorted. This argument is optional.
Return type
The same type as expression, such as DECIMAL(5,2) for a DECIMAL(5,2) expression or INTEGER for an INTEGER expression.
Examples
The following SQL query returns the amount of the next order. Order 5 gets NULL because the amount of order 6 is NULL, and order 6 gets NULL because no order follows it.
SELECT order_id, amount, lead(amount) OVER ( ORDER BY order_id ) AS next_amount FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) ORDER BY order_id
The query returns the following results.
| order_id | amount | next_amount |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query returns the customer of the next order in the same region, with 'none' as the default for the last order of each region.
SELECT region, order_id, customer, lead( customer, 1, 'none' ) OVER (PARTITION BY region ORDER BY order_id) AS next_customer FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) ORDER BY region, order_id
The query returns the following results.
| region | order_id | customer | next_customer |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query uses IGNORE NULLS to return the next reading that has a value. The next_known_or_zero column also passes an offset and a default, with IGNORE NULLS after the last argument, so the last row gets 0 instead of NULL.
SELECT reading_id, temperature, lead( temperature IGNORE NULLS ) OVER (ORDER BY reading_id) AS next_known_reading, lead( temperature, 1, 0 IGNORE NULLS ) OVER (ORDER BY reading_id) AS next_known_or_zero FROM (VALUES (1, 10), (2, NULL), (3, 30), (4, NULL), (5, 50) ) AS readings(reading_id, temperature) ORDER BY reading_id
The query returns the following results.
| reading_id | temperature | next_known_reading | next_known_or_zero |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query passes a default of 1.5 for an INTEGER column. The default is converted to INTEGER, so the last row gets 2, not 1.5.
SELECT x, lead(x, 1, 1.5) OVER (ORDER BY x) AS next_or_default FROM (VALUES (10), (20)) AS t(x) ORDER BY x
The query returns the following results.
| x | next_or_default |
|---|---|
|
|
|
|
Considerations
default is converted to the type of expression. For an INTEGER expression, a default of 1.5 becomes 2, and a default of 'none' makes the query fail. To return a value of another type, cast expression first, as in lead(CAST(.expression AS VARCHAR), 1, 'none')
Without ORDER BY in the window, the query does not define which row is the next one. If rows tie on the ORDER BY values, their order is not defined either, so add columns to ORDER BY until each row's values are unique.
Differences from Athena engine version 3
In Athena engine version 3, you write IGNORE NULLS after the closing parenthesis, as in lead(. DuckDB rejects that form with a syntax error. Write expression) IGNORE NULLS OVER (ORDER BY sort_expression)IGNORE NULLS inside the parentheses, after the last argument, as in lead( or expression IGNORE NULLS) OVER (ORDER BY sort_expression)lead(.expression, 1, 0 IGNORE NULLS) OVER (ORDER BY sort_expression)
nth_value function
Returns the value that expression has at position n of the window frame, where the first row of the frame is position 1. If the frame has fewer than n rows, the result is NULL.
When the window has an ORDER BY and no frame, the frame ends at the current row and its peers. As a result, the rows that come before position n in each partition get NULL, unless they tie with the row at position n. To read row n of the whole partition from every row, give the window the frame ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. With IGNORE NULLS, the function counts only the rows where expression is not NULL.
Syntax
nth_value(expression, n
[ IGNORE NULLS | RESPECT NULLS ]) OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] [ frame ] )
Arguments
The nth_value function takes the following arguments:
expression-
The value to return, of any data type.
n-
The position of the row in the frame, as a
BIGINTstarting at 1. IfnisNULL,0, or negative, the result isNULL. partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the function reads only the current row's partition. This argument is optional. sort_expression-
An expression that sets the order of the rows in each partition, and so the position of each row. It can be of any data type that can be sorted. This argument is optional.
frame-
A frame that limits the rows that the function reads, such as
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. For more information about frames, see OVER clause. This argument is optional.
Return type
The same type as expression, such as VARCHAR for a VARCHAR expression.
Examples
The following SQL query returns the second-place athlete of each event on every row of that event. The frame covers the whole partition.
SELECT event, athlete, points, nth_value(athlete, 2) OVER (PARTITION BY event ORDER BY points DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_place FROM (VALUES ('relay', 'ana', 90), ('relay', 'ben', 85), ('relay', 'cai', 80), ('relay', 'dev', 70), ('sprint', 'fay', 95), ('sprint', 'gus', 80) ) AS results(event, athlete, points) ORDER BY event, points DESC
The query returns the following results.
| event | athlete | points | second_place |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query runs the same call with the default frame, which ends at the current row and its peers. The first row of each event has only one row in its frame, so it gets NULL.
SELECT event, athlete, points, nth_value(athlete, 2) OVER ( PARTITION BY event ORDER BY points DESC ) AS second_place_so_far FROM (VALUES ('relay', 'ana', 90), ('relay', 'ben', 85), ('relay', 'cai', 80), ('relay', 'dev', 70), ('sprint', 'fay', 95), ('sprint', 'gus', 80) ) AS results(event, athlete, points) ORDER BY event, points DESC
The query returns the following results.
| event | athlete | points | second_place_so_far |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query compares nth_value with and without IGNORE NULLS over the whole partition. Without it, the second row is reading 2. With it, the function counts only the readings that have a value, so the second one is reading 4.
SELECT reading_id, temperature, nth_value( temperature, 2 ) OVER w AS second_reading, nth_value( temperature, 2 IGNORE NULLS ) OVER w AS second_known_reading FROM (VALUES (1, NULL), (2, 20), (3, NULL), (4, 40) ) AS readings(reading_id, temperature) WINDOW w AS ( ORDER BY reading_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) ORDER BY reading_id
The query returns the following results.
| reading_id | temperature | second_reading | second_known_reading |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
If rows tie on the ORDER BY values, the query does not define their positions, so the row at position n can change from one run to the next. Add columns to ORDER BY until each row's values are unique.
Differences from Athena engine version 3
In Athena engine version 3, you write IGNORE NULLS after the closing parenthesis, as in nth_value(. DuckDB rejects that form with a syntax error. Write expression, n) IGNORE NULLS OVER (ORDER BY sort_expression)IGNORE NULLS inside the parentheses, after n, as in nth_value(.expression, n IGNORE NULLS) OVER (ORDER BY sort_expression)
ntile function
Divides the rows of the partition, in the order that the window's ORDER BY sets, into num_buckets buckets whose sizes differ by at most one row. It returns the number of the bucket that the current row belongs to, starting at 1. When the rows do not divide evenly, the first buckets get one extra row each. For example, 7 rows in 3 buckets gives buckets of 3, 2, and 2 rows.
If the partition has fewer rows than num_buckets, each row gets a bucket of its own, and the bucket numbers stop at the number of rows. Rows that tie on the ORDER BY values can land in different buckets.
Syntax
ntile(num_buckets) OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] )
Arguments
The ntile function takes the following arguments:
num_buckets-
The number of buckets, as a
BIGINTgreater than 0. Ifnum_bucketsisNULL, the result isNULL. partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and each partition is divided into its own buckets. This argument is optional. sort_expression-
An expression that sets the order in which the function assigns rows to buckets. It can be of any data type that can be sorted. This argument is optional.
Return type
BIGINT
Examples
The following SQL query divides seven athletes into three buckets by points. Seven rows do not divide evenly into three buckets, so the first bucket gets the extra row.
SELECT athlete, points, ntile(3) OVER ( ORDER BY points DESC ) AS points_group FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 80), ('dev', 75), ('eli', 70), ('fay', 65), ('gus', 60) ) AS results(athlete, points) ORDER BY points DESC
The query returns the following results.
| athlete | points | points_group |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query asks for five buckets for three rows. Each row gets its own bucket, and buckets 4 and 5 stay empty.
SELECT athlete, points, ntile(5) OVER ( ORDER BY points DESC ) AS points_group FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 80) ) AS results(athlete, points) ORDER BY points DESC
The query returns the following results.
| athlete | points | points_group |
|---|---|---|
|
|
|
|
|
|
|
|
|
Considerations
If num_buckets is 0 or negative, the query fails. The query also fails when num_buckets is not an integer, such as 2.5, or when it has the type DOUBLE, even if its value is a whole number. For example, ntile(4 / 2) fails because / returns a DOUBLE. To use a computed value, cast it to BIGINT, as in ntile(CAST(4 / 2 AS BIGINT)).
Without ORDER BY in the window, the query does not define which rows go into which bucket.
OVER clause
The OVER clause makes a function call a window function call and defines its window. PARTITION BY splits the rows into partitions, and the function runs separately on each partition. ORDER BY sets the order of the rows in each partition. The frame limits the rows that the function reads for each row. Each part is optional. OVER () treats all the rows of the query as one partition, in no defined order.
Instead of a window definition, OVER can name a window from the query's WINDOW clause, as in OVER w. Inside the parentheses, you can start from a named window and add to it. For example, write OVER (w ORDER BY amount DESC) or OVER (w ROWS BETWEEN 1 PRECEDING AND CURRENT ROW). You can add an ORDER BY only to a named window that has no ORDER BY of its own. If the named window already has one, the query fails. For more information about named windows, see WINDOW clause.
A frame has a unit, a start, and an end. With ROWS, an offset counts rows. With GROUPS, it counts groups of peers, the rows that have the same ORDER BY values. With RANGE, it is a distance from the current row's ORDER BY value, such as 10 for a number or INTERVAL 1 DAY for a date. A RANGE frame with an offset needs exactly one ORDER BY expression. If you give only a start, as in ROWS 2 PRECEDING, the frame ends at the current row.
EXCLUDE CURRENT ROW removes the current row from the frame, EXCLUDE GROUP removes the current row and its peers, and EXCLUDE TIES removes only its peers. EXCLUDE NO OTHERS, the default, removes nothing.
IGNORE NULLS and RESPECT NULLS apply to first_value, last_value, nth_value, lag, and lead. The aggregate functions first and last also accept IGNORE NULLS when you use them with OVER. The ranking functions, fill, and the other aggregate functions do not accept IGNORE NULLS. FILTER applies only to aggregate functions.
Syntax
function( [ DISTINCT ] [ argument [, ...] ]
[ IGNORE NULLS | RESPECT NULLS ] )
[ FILTER ( WHERE condition ) ] OVER
{ window_name | ( window_definition ) }
window_definition: [ window_name ]
[ PARTITION BY expression [, ...] ]
[ ORDER BY expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] [ frame ]
frame: { ROWS | RANGE | GROUPS }
{ frame_start
| BETWEEN frame_start AND frame_end } [ EXCLUDE
{ CURRENT ROW | GROUP | TIES | NO OTHERS } ]
frame_start, frame_end: UNBOUNDED PRECEDING
| offset PRECEDING | CURRENT ROW
| offset FOLLOWING | UNBOUNDED FOLLOWING
Examples
The following SQL query computes each region's total, a running total in each region in order of order_id, and the number of orders in each region. The sum function skips the NULL amount of order 6, so the running total for order 6 stays at 162.75.
SELECT region, order_id, amount, sum(amount) OVER ( PARTITION BY region ) AS region_total, sum(amount) OVER ( PARTITION BY region ORDER BY order_id ) AS running_total, count(*) OVER ( PARTITION BY region ) AS region_orders FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) ORDER BY region, order_id
The query returns the following results.
| region | order_id | amount | region_total | running_total | region_orders |
|---|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query compares the default frame with a ROWS frame and with a window that has no ORDER BY. Two rows share the date 2026-10-01. The default frame includes both of them, so both get the running total 150. The ROWS frame stops at the current row, and its ORDER BY adds amount so that the order of the two rows is defined. Without ORDER BY, the frame is the whole partition.
SELECT day, amount, sum(amount) OVER ( ORDER BY day ) AS default_frame_total, sum(amount) OVER ( ORDER BY day, amount DESC ROWS UNBOUNDED PRECEDING ) AS rows_frame_total, sum(amount) OVER () AS grand_total FROM (VALUES (DATE '2026-10-01', 100), (DATE '2026-10-01', 50), (DATE '2026-10-02', 30), (DATE '2026-10-04', 20), (DATE '2026-10-05', 10) ) AS daily(day, amount) ORDER BY day, amount DESC
The query returns the following results.
| day | amount | default_frame_total | rows_frame_total | grand_total |
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query compares the three frame units. Each frame covers the current row and reaches one unit back. ROWS adds the previous row, RANGE adds the rows from the previous day, and GROUPS adds the previous group of rows that share a date. The RANGE and GROUPS frames also cover the other rows that share the current row's date. On 2026-10-04, the previous day has no rows, so the RANGE frame holds only the current row, while the GROUPS frame reaches back to 2026-10-02.
SELECT day, amount, sum(amount) OVER ( ORDER BY day, amount DESC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW ) AS rows_sum, sum(amount) OVER ( ORDER BY day RANGE BETWEEN INTERVAL 1 DAY PRECEDING AND CURRENT ROW ) AS range_sum, sum(amount) OVER ( ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW ) AS groups_sum FROM (VALUES (DATE '2026-10-01', 100), (DATE '2026-10-01', 50), (DATE '2026-10-02', 30), (DATE '2026-10-04', 20), (DATE '2026-10-05', 10) ) AS daily(day, amount) ORDER BY day, amount DESC
The query returns the following results.
| day | amount | rows_sum | range_sum | groups_sum |
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query uses EXCLUDE CURRENT ROW to total the amounts of the orders immediately before and after each order. It also uses FILTER to count the orders over 50 so far, and DISTINCT to count the distinct regions so far.
SELECT order_id, amount, sum(amount) OVER ( ORDER BY order_id ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING EXCLUDE CURRENT ROW ) AS neighbors_total, count(*) FILTER ( WHERE amount > 50 ) OVER (ORDER BY order_id) AS large_orders_so_far, count( DISTINCT region ) OVER (ORDER BY order_id) AS regions_so_far FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) ORDER BY order_id
The query returns the following results.
| order_id | amount | neighbors_total | large_orders_so_far | regions_so_far |
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
A window function cannot appear in a WHERE clause or inside another window function call. Both make the query fail. To filter on the result of a window function, use QUALIFY, or compute it in a subquery and filter in the outer query.
When the ORDER BY of a window has ties, a ROWS frame can split the peers in any order. As a result, a running total over ROWS can differ from one run to the next for tied rows. To get the same result every time, add columns to ORDER BY until each row's values are unique, or use the default RANGE frame, which treats peers as one group.
percent_rank function
Divides the current row's rank minus 1 by the number of rows in the partition minus 1, and returns the result. The rank is the value that rank returns for the current row. The first row of a partition, and every row that ties with it, gets 0. The last row gets 1, unless it ties with earlier rows. When a partition has only one row, that row gets 0.
To get the fraction of rows that sort before the current row or tie with it, use the cume_dist function.
Syntax
percent_rank() OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] )
Arguments
The percent_rank function takes the following arguments:
partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the function is computed separately for each partition. This argument is optional. sort_expression-
An expression that sets the order in which the rows are ranked. It can be of any data type that can be sorted. Rows that have the same values for every
sort_expressionget the same result. This argument is optional.
Return type
DOUBLE
Examples
The following SQL query returns the relative rank of five athletes. The athletes ben and cai tie for rank 2, so both get (2 - 1) / (5 - 1), which is 0.25.
SELECT athlete, points, percent_rank() OVER ( ORDER BY points DESC ) AS relative_rank FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 85), ('dev', 70), ('eli', 60) ) AS results(athlete, points) ORDER BY points DESC, athlete
The query returns the following results.
| athlete | points | relative_rank |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query computes the relative rank in each event. The sprint event has only one athlete, so that row gets 0.
SELECT event, athlete, points, percent_rank() OVER ( PARTITION BY event ORDER BY points DESC ) AS relative_rank FROM (VALUES ('relay', 'ana', 90), ('relay', 'ben', 85), ('relay', 'cai', 70), ('sprint', 'fay', 95) ) AS results(event, athlete, points) ORDER BY event, points DESC
The query returns the following results.
| event | athlete | points | relative_rank |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Considerations
Without ORDER BY in the window, all the rows of a partition are peers, so every row gets 0.
rank function
Returns the rank of the current row in its partition, in the order that the window's ORDER BY sets. Rows that tie on the ORDER BY values, called peers, get the same rank. The next rank skips the numbers that the tied rows used up. For example, if two rows tie for rank 2, the next row has rank 4. Put another way, the rank of a row is 1 plus the number of rows in its partition whose ORDER BY values come before its own.
To rank without gaps, use dense_rank. To get the rank as a fraction from 0 to 1, use percent_rank.
Syntax
rank() OVER ( [ PARTITION BY partition_expression
[, ...] ] [ ORDER BY sort_expression
[ ASC | DESC ] [ NULLS { FIRST | LAST } ]
[, ...] ] )
Arguments
The rank function takes the following arguments:
partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the ranks start again at 1 in each partition. This argument is optional. sort_expression-
An expression that sets the order in which the rows are ranked. It can be of any data type that can be sorted. Rows that have the same values for every
sort_expressionget the same rank. This argument is optional.
Return type
BIGINT
Examples
The following SQL query ranks the athletes in each event by points. ben and cai tie for rank 2 in the relay, so the next athlete has rank 4.
SELECT event, athlete, points, rank() OVER ( PARTITION BY event ORDER BY points DESC ) AS rank_in_event FROM (VALUES ('relay', 'ana', 90), ('relay', 'ben', 85), ('relay', 'cai', 85), ('relay', 'dev', 70), ('relay', 'eli', 60), ('sprint', 'fay', 95), ('sprint', 'gus', 80) ) AS results(event, athlete, points) ORDER BY event, rank_in_event, athlete
The query returns the following results.
| event | athlete | points | rank_in_event |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query ranks the regions by their total sales. In a grouped query, the window's ORDER BY can use an aggregate function.
SELECT region, sum(amount) AS total, rank() OVER ( ORDER BY sum(amount) DESC ) AS total_rank FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) GROUP BY region ORDER BY total_rank
The query returns the following results.
| region | total | total_rank |
|---|---|---|
|
|
|
|
|
|
|
|
|
The following SQL query keeps the athletes whose rank is at most 3. The athletes ben and cai tie for rank 3, so the query returns four rows, the same rows that FETCH FIRST 3 ROWS WITH TIES returns in Athena engine version 3.
SELECT athlete, points FROM (VALUES ('relay', 'ana', 90), ('relay', 'ben', 85), ('relay', 'cai', 85), ('relay', 'dev', 70), ('relay', 'eli', 60), ('sprint', 'fay', 95), ('sprint', 'gus', 80) ) AS results(event, athlete, points) QUALIFY rank() OVER (ORDER BY points DESC) <= 3 ORDER BY points DESC, athlete
The query returns the following results.
| athlete | points |
|---|---|
|
|
|
|
|
|
|
|
The following SQL query calls rank with an empty OVER clause. With no ORDER BY, every row is a peer of every other row, so every row has rank 1.
SELECT athlete, rank() OVER () AS rank_without_order FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 70) ) AS results(athlete, points) ORDER BY athlete
The query returns the following results.
| athlete | rank_without_order |
|---|---|
|
|
|
|
|
|
Considerations
Without ORDER BY in the window, all the rows of a partition are peers, so every row has rank 1.
NULL values of sort_expression tie with each other and, by default, sort after all other values, so they share the last rank.
Differences from Athena engine version 3
Athena engine version 3 supports FETCH FIRST , which also returns the rows that tie with the last row. DuckDB does not support n ROWS WITH TIESWITH TIES. To get the same rows, filter on rank with QUALIFY, as in QUALIFY rank() OVER (ORDER BY .sort_expression) <= n
row_number function
Returns the position of the current row in its partition, in the order that the window's ORDER BY sets. The first row gets 1, the second row gets 2, and so on. Every row gets a different number, even rows that tie on the ORDER BY values. To give tied rows the same number, use the rank function or the dense_rank function.
To keep one row from each group, such as the latest version of each record, filter on row_number with QUALIFY.
Syntax
row_number() OVER (
[ PARTITION BY partition_expression [, ...] ]
[ ORDER BY sort_expression [ ASC | DESC ] [ NULLS
{ FIRST | LAST } ] [, ...] ] )
Arguments
The row_number function takes the following arguments:
partition_expression-
An expression that splits the rows into partitions. It can be of any data type. Rows that have the same values for every
partition_expressionform one partition, and the numbering starts again at 1 in each partition. This argument is optional. sort_expression-
An expression that sets the order in which the rows of each partition are numbered. It can be of any data type that can be sorted. This argument is optional.
Return type
BIGINT
Examples
The following SQL query numbers the orders in each region, starting from the lowest order ID.
SELECT region, order_id, customer, row_number() OVER ( PARTITION BY region ORDER BY order_id ) AS order_number FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) ORDER BY region, order_number
The query returns the following results.
| region | order_id | customer | order_number |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query numbers athletes by points. ben and cai tie on 85 points, so the window's ORDER BY adds athlete to decide which of them comes first.
SELECT athlete, points, row_number() OVER ( ORDER BY points DESC, athlete ) AS position FROM (VALUES ('ana', 90), ('ben', 85), ('cai', 85), ('dev', 70), ('eli', 60) ) AS results(athlete, points) ORDER BY position
The query returns the following results.
| athlete | points | position |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query keeps only the latest version of each customer's status, by numbering the versions of each customer from the newest and keeping number 1.
SELECT customer, version, status FROM (VALUES ('alice', 1, 'pending'), ('alice', 2, 'shipped'), ('bob', 1, 'pending'), ('carol', 1, 'pending'), ('carol', 2, 'shipped'), ('carol', 3, 'delivered') ) AS updates(customer, version, status) QUALIFY row_number() OVER ( PARTITION BY customer ORDER BY version DESC ) = 1 ORDER BY customer
The query returns the following results.
| customer | version | status |
|---|---|---|
|
|
|
|
|
|
|
|
|
Considerations
When rows tie on the ORDER BY values, or when the window has no ORDER BY, the query does not define which of those rows gets which number. The numbers can change from one run to the next. To get the same numbers every time, add columns to ORDER BY until each row's values are unique, as in ORDER BY points DESC, athlete.