Skip to main content

LeetCode 183. Customers Who Never Order SQL Solution

Problem

LeetCode SQL Problem

  1. Customers Who Never Order

Customers table

IdName
1Joe
2Henry
3Sam
4Max
5Bob

Orders table

IdCustomerId
13
21
32
41

Solution - LEFT JOIN

Customers Who Never Order
-- Find Customer Id that does not appear in Orders table at all using LEFT JOIN
SELECT C.Name AS Customers
FROM Customers AS C
LEFT JOIN Orders AS O ON C.Id = O.CustomerId
WHERE O.Id IS NULL;

Solution - EXISTS + Correlated Subquery

Customers Who Never Order
-- Find Customer Id that does not appear in Orders table at all using EXISTS and correlated subquery
SELECT C.Name AS Customers
FROM Customers AS C
WHERE NOT EXISTS (
SELECT *
FROM Orders AS O
WHERE O.CustomerId = C.Id
)

Solution - IN + Subquery

Customers Who Never Order
-- Find Customer Id that does not appear in Orders table at all using IN and Subquery
SELECT C.Name AS Customers
FROM Customers AS C
WHERE C.Id NOT IN (
SELECT O.CustomerId
FROM Orders AS O
)

Query Output

Customers
Max
Bob