-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomers_never_ordered.sql
58 lines (45 loc) · 1.04 KB
/
customers_never_ordered.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
use master;
drop database if exists x_customers_never_ordered;
create database x_customers_never_ordered;
go
use x_customers_never_ordered;
go
create table Customers (
id int not null,
name varchar(50) not null,
primary key (id)
);
create table Orders (
id int not null,
customerId int not null,
primary key (id)
);
alter table Orders
add constraint FK_Orders_customerId
foreign key (customerId)
references Customers (id);
insert into Customers (id, name) values
(1, 'Joe'),
(2, 'Henry'),
(3, 'Sam'),
(4, 'Max');
insert into Orders (id, customerId) values
(1, 3),
(2, 1);
-- expected output
--------------------------------------------------------
-- Customers
--------------------------------------------------------
-- Henry
-- Max
-- solution 1
select c.name as Customers
from Customers c
left join Orders o on c.id = o.customerId
where o.id is null;
-- solution 2
select c.name as Customers
from Customers c
where c.id not in (
select customerId from Orders
);