Medium Subqueries and CTEs Employees database

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

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

name
Engineering
Marketing
Support

Rows can come in any order. Column names do not have to match.

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.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.