-
Notifications
You must be signed in to change notification settings - Fork 43
/
students-with-invalid-departments.sql
93 lines (80 loc) · 2.34 KB
/
students-with-invalid-departments.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
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 |
+------+----------+
*/
# V0
# V1
# https://code.dennyzhang.com/students-with-invalid-departments
select id, name
from Students
where department_id not in
(select id from Departments)
# V2
# Time: O(n)
# Space: O(n)
SELECT s.id,
s.name
FROM students s
LEFT JOIN departments d
ON d.id = s.department_id
WHERE d.id IS NULL;
# Time: O(n)
# Space: O(n)
SELECT s.id,
s.name
FROM students s
WHERE NOT EXISTS (SELECT id
FROM departments d
WHERE d.id = s.department_id);