QUALIFY Clause in SQL
- The
QUALIFY
clause filters the results of window functions. - This filtering of results is similar to how a
HAVING
clause filters the results of aggregate functions applied based on theGROUP BY
clause. - A window function is required to be present either in the
QUALIFY
clause or theSELECT
list. - The QUALIFY clause avoids the need for a subquery or WITH clause to perform this filtering (much like HAVING avoids a subquery).
The evaluation of a query with a QUALIFY
clause is typically completed in this order:
FROM
WHERE
GROUP BY
and aggregationHAVING
(filters the results of aggregation)WINDOW
QUALIFY
(filters the results of window functions)DISTINCT
ORDER BY
LIMIT
Example
Lets create a table employee
with the following data:
Find Employees with Lowest Salary for Each Job Title
Using CTE:
Output:
emp_name | job_title | city | salary |
---|---|---|---|
Rohit | Software Engineer | Delhi | 500000 |
Megha | Data Scientist | Bangalore | 800000 |
Anjali | HR Manager | Bangalore | 400000 |
Using Sub-query:
Output:
emp_name | job_title | city | salary |
---|---|---|---|
Rohit | Software Engineer | Delhi | 500000 |
Megha | Data Scientist | Bangalore | 800000 |
Anjali | HR Manager | Bangalore | 400000 |
Using QUALIFY
clause:
Output:
emp_name | job_title | city | salary |
---|---|---|---|
Rohit | Software Engineer | Delhi | 500000 |
Megha | Data Scientist | Bangalore | 800000 |
Anjali | HR Manager | Bangalore | 400000 |
Different ways to write the same query using QUALFIY
clause to get the same result.
QUALIFY
is not part of the ANSI SQL standard. So it is not supported in all databases.QUALFIY clause is a powerful feature in SQL that can be used to filter the results of window functions without the need for a subquery or WITH clause. It is a great way to simplify the SQL query and make it more readable. Since it is not part of the ANSI SQL standard, it is not supported in many databases like SQL server, spark. Currently supported in databricks, snowflake, bigquery, teradata and duckdb.