Check for related rows with EXISTS
Question
Show the name of departments that have at least one employee hired in 2022 or later.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| name |
|---|
| Engineering |
| Marketing |
| Support |
Hint
EXISTS (subquery) is true when the subquery returns at least one row.
Show the solution
solution.sql
Run this code
SELECT d.name
FROM departments d
WHERE EXISTS (
SELECT 1
FROM employees e
WHERE e.department_id = d.id AND e.hired_on >= '2022-01-01'
);
Why it works
For each department, the subquery looks for a matching recent hire. EXISTS only cares whether a row exists, so SELECT 1 is enough, and each department appears once.
Common mistake
A JOIN would repeat a department for every recent hire. EXISTS answers the yes or no question without duplicates.