The SQL QUALIFY statement is used to filter the results of a query that uses window functions. It was introduced in SQL:2011, the sixth edition of the SQL standard.
History
The QUALIFY clause was added to the SQL standard to provide a way to filter the results of a query that uses window functions, such as ROW_NUMBER(), RANK(), and NTILE(). Prior to the introduction of QUALIFY, it was necessary to use a subquery or a Common Table Expression (CTE) to filter the results of a query that used window functions.
Syntax
The syntax of the QUALIFY statement is as follows:
sql
SELECT column1, column2, ...
FROM table_name
QUALIFY condition;
The QUALIFY clause is used to specify a condition that must be met for a row to be included in the result set.
Example
The following example uses the QUALIFY clause to filter the results of a query that uses the ROW_NUMBER() window function:
sql
SELECT employee_id, name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM employees
QUALIFY row_num <= 5;
This query returns the top 5 employees with the highest salaries.
The QUALIFY clause is supported by the following databases:
PostgreSQL
MySQL (version 8.0 and later)
Google BigQuery
Amazon Redshift
Note that not all databases support the QUALIFY clause, so it's always a good idea to check the documentation for your specific database to see if it's supported.