sqlsql-serversubquery

Case of null value based on key column when returning rows without a certain match in another table


The employee table lists the employees and the history table records hire and term dates as separate rows.

I need to write a query that identifies all employees from the employee table that are terminated but do not have a term record in the history table.

Employee:

Emp_ID Emp_Name Term_Flag
1 Sally No
2 Lucy Yes
3 Marcie Yes

Emp_History:

Emp_ID Emp_Date Reason_Code
1 1/1/2024 Hire
2 1/1/2023 Hire
2 12/31/2024 Term
3 1/1/2025 Hire

My query should return Marcie, because she is terminated (term flag = yes) but has no Term record in the history table

How do I return null values based on the key column?


Solution

  • A common way to find records not linked to a second table is a LEFT join, in this case adding the 'Term' condition.

    SELECT Emp_ID, Emp_Name 
    FROM Employee e
    LEFT JOIN Emp_History eh ON eh.Emp_ID = e.Emp_ID and eh.Reason_Code = 'Term'
    WHERE 
    e.Term_Flag = 'Yes' and eh.Emp_Id IS NULL