Students With Invalid Departments Problem
Description
LeetCode Problem 1350.
Table: Departments
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
id is the primary key of this table.
The table has information about the id of each department of a university.
Table: Students
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
| department_id | int |
+---------------+---------+
id is the primary key of this table.
The table has information about the id of each student at a university and the id of the department he/she studies at.
Write an SQL query to find the id and the name of all students who are enrolled in departments that no longer exists.
Return the result table in any order.
The query result format is in the following example:
Departments table:
+------+--------------------------+
| id | name |
+------+--------------------------+
| 1 | Electrical Engineering |
| 7 | Computer Engineering |
| 13 | Bussiness Administration |
+------+--------------------------+
Students table:
+------+----------+---------------+
| id | name | department_id |
+------+----------+---------------+
| 23 | Alice | 1 |
| 1 | Bob | 7 |
| 5 | Jennifer | 13 |
| 2 | John | 14 |
| 4 | Jasmine | 77 |
| 3 | Steve | 74 |
| 6 | Luis | 1 |
| 8 | Jonathan | 7 |
| 7 | Daiana | 33 |
| 11 | Madelynn | 1 |
+------+----------+---------------+
Result table:
+------+----------+
| id | name |
+------+----------+
| 2 | John |
| 7 | Daiana |
| 4 | Jasmine |
| 3 | Steve |
+------+----------+
John, Daiana, Steve and Jasmine are enrolled in departments 14, 33, 74 and 77 respectively. department 14, 33, 74 and 77 doesn't exist in the Departments table.
Solution
Approach: Anti-Join with LEFT JOIN
We want the students whose department_id has no matching row in Departments. That is an anti-join: keep the rows of one table that find no partner in the other.
LEFT JOINDepartmentsond.id = s.department_id. Every student is kept; when the department does not exist, theDepartmentscolumns areNULL.- Keep only those rows with
WHERE d.id IS NULL.
WHERE department_id NOT IN (SELECT id FROM Departments) gives the same answer here, but NOT IN is fragile around NULLs: if the list or the left side contains a NULL, the comparison is unknown and rows silently disappear. The LEFT JOIN ... IS NULL form (or NOT EXISTS) has no such trap.
The Pandas version keeps the students whose department_id is not in departments["id"], using isin.
SELECT s.id,
s.name
FROM Students AS s
LEFT JOIN Departments AS d
ON d.id = s.department_id
WHERE d.id IS NULL; -- no department with that id