- Categories:
QUALIFY¶
In a SELECT statement, the QUALIFY clause filters the results of window functions.
QUALIFY does with window functions what HAVING does with aggregate functions and GROUP BY clauses.
In the execution order of a query, QUALIFY is therefore evaluated after window functions are computed. Typically, a SELECT statement’s clauses are evaluated in the order shown below:
FROM
WHERE
GROUP BY
HAVING
WINDOW
QUALIFY
DISTINCT
ORDER BY
LIMIT
Syntax¶
The general form of a statement with QUALIFY is similar to the following (some variations in order are allowed, but are not shown):
Parameters¶
column_listThis generally follows the rules for the projection clause of a SELECT statement.
data_sourceThe data source is usually a table, but can be another table-like data source, such as a view, UDTF (user-defined table function), etc.
predicateThe predicate is an expression that filters the result after aggregates and window functions are computed. The predicate should look similar to a HAVING clause, but without the keyword HAVING. In addition, the predicate can also contain window functions.
See the Examples section (in this topic) for predicate examples.
Usage notes¶
The QUALIFY clause requires at least one window function to be specified in at least one of the following clauses of the SELECT statement:
The SELECT column list.
The filter predicate of the QUALIFY clause.
Examples of each of these are shown in the Examples section below.
Expressions in the SELECT list, including window functions, can be referred to by the column alias defined in the SELECT list.
QUALIFY supports aggregates and subqueries in the predicate. For aggregates, the same rules as for the HAVING clause apply.
The word QUALIFY is a reserved word.
The Snowflake syntax for QUALIFY is not part of the ANSI standard.
Examples¶
The QUALIFY clause simplifies queries that require filtering on the result of window functions. Without QUALIFY, filtering requires nesting. The example below uses the ROW_NUMBER() function to return only the first row in each partition.
Create and load a table:
This query uses nesting rather than QUALIFY:
This query uses QUALIFY:
You can also use QUALIFY to reference window functions that are in the SELECT column list:
You can see how QUALIFY acts as a filter by removing it from the previous query and comparing the output:
The QUALIFY clause can also be combined with aggregate functions and subqueries in the predicate. In such a query, HAVING filters rows after GROUP BY aggregation, while QUALIFY filters rows after window functions are computed. Both clauses can appear together when a query requires both kinds of filtering. For example: