Given the following schema: employees(emp-id, first-name, last-name,…

2014

Given the following schema:

employees(emp-id, first-name, last-name, hire-date,dept-id, salary)

departments(dept-id, dept-name, manager-id, location-id)

You want to display the last names and hire dates of all latest hires in their respective departments in the location ID 1700. You issue the following query:

SQL>SELECT last-name, hire-date FROM employees WHERE (dept-id, hire-date) IN (SELECT dept-id, MAX(hire-date) FROM employees JOIN departments USING(dept-id) WHERE location-id =1700 GROUP BY dept-id);

What is the outcome?

  1. A.

    It executes but does not give the correct result.

  2. B.

    It executes and gives the correct result.

  3. C.

    It generates an error because of pairwise comparison.

  4. D.

    It generates an error because the GROUP BY clause cannot be used with table joins in a subquery.

Attempted by 101 students.

Show answer & explanation

Correct answer: B

Answer: The query executes and gives the correct result.

Explanation:

  • The subquery SELECT dept-id, MAX(hire-date) FROM employees JOIN departments USING(dept-id) WHERE location-id =1700 GROUP BY dept-id returns one pair (dept-id, max_hire_date) for each department located at 1700.

  • The outer WHERE (dept-id, hire-date) IN ( ... ) performs a row-value comparison: it selects employees whose department and hire-date match one of those (dept-id, max_hire_date) pairs, so the latest hire(s) per department are returned.

  • If multiple employees in a department share the same maximum hire-date, all of them will be returned because their (dept-id, hire-date) pair matches the subquery result.

  • Portability note: row-value IN comparisons are supported by Oracle and many SQL dialects. If you are using a DBMS that does not support row constructors, rewrite the logic using EXISTS or a join with an aggregated subquery.

Alternative (correlated subquery) if row-value comparisons are not supported:

SELECT e.last_name, e.hire_date FROM employees e WHERE e.hire_date = (SELECT MAX(e2.hire_date) FROM employees e2 WHERE e2.dept_id = e.dept_id) AND EXISTS (SELECT 1 FROM departments d WHERE d.dept_id = e.dept_id AND d.location_id = 1700);

Alternative (join with aggregated subquery):

SELECT e.last_name, e.hire_date FROM employees e JOIN (SELECT dept_id, MAX(hire_date) AS max_hire FROM employees GROUP BY dept_id) m ON e.dept_id = m.dept_id AND e.hire_date = m.max_hire JOIN departments d ON e.dept_id = d.dept_id WHERE d.location_id = 1700;

Summary: The original query is valid and returns the latest hires per department at location 1700. Use the alternatives shown when your SQL dialect does not permit row-value comparisons.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir