Description

Table: Departments

Column NameType
idint
namevarchar
  • In SQL, id is the primary key of this table.
  • The table has information about the id of each department of a university.

Table: Students

Column NameType
idint
namevarchar
department_idint
  • In SQL, 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.

Problem Statement

Find the id and the name of all students who are enrolled in departments that no longer exist.

Return the result table in any order.

The result format is in the following example.

Example 1:

Input:

  • Departments table:
idname
1Electrical Engineering
7Computer Engineering
13Bussiness Administration
  • Students table:
idnamedepartment_id
23Alice1
1Bob7
5Jennifer13
2John14
4Jasmine77
3Steve74
6Luis1
8Jonathan7
7Daiana33
11Madelynn1

Output:

idname
2John
7Daiana
4Jasmine
3Steve

Explanation:

  • John, Daiana, Steve, and Jasmine are enrolled in departments 14, 33, 74, and 77 respectively. department 14, 33, 74, and 77 do not exist in the Departments table.

Solution

You do need to join the two tables based on deparment_id. You have to join as outer join and can help fetch the students who are enrolled in non-existing department.

1SELECT s.id, s.name 
2    FROM Students s
3    LEFT OUTER JOIN Departments d
4    ON s.department_id = d.id
5    WHERE d.id IS NULL;