Find Employees with Lowest Salary for Each Job Title
Using CTE:
Copy
WITH ranked_employees AS ( SELECT emp_name, job_title, city, salary, RANK() OVER (PARTITION BY job_title ORDER BY salary) AS rank FROM employee)SELECT emp_name, job_title, city, salaryFROM ranked_employeesWHERE rank = 1;
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:
Copy
SELECT emp_name, job_title, city, salaryFROM ( SELECT emp_name, job_title, city, salary, RANK() OVER (PARTITION BY job_title ORDER BY salary) AS rank FROM employee) AS ranked_employeesWHERE rank = 1;
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:
Copy
/* Window function in QUALIFY clause*/SELECT emp_name, job_title, city, salaryFROM employeeQUALIFY RANK() OVER (PARTITION BY job_title ORDER BY salary) = 1;
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.
Window function in SELECT column list
Copy
SELECT emp_name, job_title, city, salary,RANK() OVER (PARTITION BY job_title ORDER BY salary) AS emp_rankFROM employeeQUALIFY emp_rank = 1;
Window function in the QUALIFY clause but using WINDOW clause
Copy
SELECT emp_name, job_title, city, salaryFROM employeeWINDOW w AS (PARTITION BY job_title ORDER BY salary)QUALIFY RANK() OVER(w) = 1;
Window function in the SELECT clause but using WINDOW clause
Copy
SELECT emp_name, job_title, city, salary,RANK() OVER (w) AS emp_rankFROM employeeWINDOW w AS (PARTITION BY job_title ORDER BY salary)QUALIFY emp_rank = 1;
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.