cswork / libraryOpen practice workspace

Coding questions · Amazon

Identify Employees with Invalid Department References

This question evaluates SQL data manipulation skills and data-quality reasoning, specifically assessing understanding of referential integrity and the detection of orphaned foreign-key references between related tables.

EMPLOYEE

+-----+-----+--------+
| eid | did | ename  |
+-----+-----+--------+
| 1   | 10  | Alice  |
| 2   | 11  | Bob    |
| 3   | 99  | Carol  |
+-----+-----+--------+

DEPARTMENT

+-----+---------+
| did | dname   |
+-----+---------+
| 10  | Sales   |
| 11  | Finance |
+-----+---------+
Scenario

A company database holds EMPLOYEE and DEPARTMENT tables. Management needs to find employees referencing non-existent departments so the data can be cleaned.

Question

Using SQL, return all rows from EMPLOYEE whose did is not present in DEPARTMENT.

Hints

Think anti-join patterns such as LEFT JOIN … WHERE department.did IS NULL, or use NOT EXISTS/NOT IN.

Find employees with non-existent departments

Table EMPLOYEE

columntypeconstraints
eidINTEGERPRIMARY KEY, NOT NULL
didINTEGERNOT NULL
enameVARCHARNOT NULL

Sample data:

dideidename
101Alice
112Bob
993Carol

Table DEPARTMENT

columntypeconstraints
didINTEGERPRIMARY KEY, NOT NULL
dnameVARCHARNOT NULL

Sample data:

diddname
10Sales
11Finance

Expected output

All EMPLOYEE rows where did has no matching did in DEPARTMENT.

dideidename
993Carol

Hints

  1. Use an anti-join: LEFT JOIN DEPARTMENT d ON d.did = e.did and filter WHERE d.did IS NULL.
  2. Or use NOT EXISTS to check absence of a matching department row.
  3. If using NOT IN, beware of NULLs in the subquery.