QUALIFY clause
Use the QUALIFY clause to keep or drop rows based on the results of window functions. DuckDB computes the window functions first and then applies the QUALIFY condition. As a result, you can filter on a value such as row_number() OVER (PARTITION BY region ORDER BY amount DESC) in the same query instead of in an outer query. The condition can call window functions directly or refer to the alias of a window function in the select list.
Syntax
QUALIFY condition
Examples
For a description of the sample tables that the examples on this page use, see SELECT statement in DuckDB.
The following SQL query keeps the largest order in each region.
SELECT region, customer, amount FROM sales_db.sales_parquet QUALIFY row_number() OVER ( PARTITION BY region ORDER BY amount DESC NULLS LAST ) = 1 ORDER BY region
The query returns the following results.
| region | customer | amount |
|---|---|---|
|
|
|
|
|
|
|
|
|
The following SQL query keeps the two largest orders in each region, and filters on the alias of the window function.
SELECT region, customer, rank() OVER ( PARTITION BY region ORDER BY amount DESC NULLS LAST ) AS rank_in_region FROM sales_db.sales_parquet QUALIFY rank_in_region <= 2 ORDER BY region, rank_in_region
The query returns the following results.
| region | customer | rank_in_region |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|