183. Customers Who Never Order

Description

Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

Table: Customers.

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Table: Orders.

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

Using the above tables as example, return the following:

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

My Solution

Source Code

1
2
3
4
5
SELECT [Name] as 'Customers'
FROM Customers as c
LEFT JOIN Orders as o
ON c.id = o.customerId
WHERE o.id IS NULL

Analysis

This one was easy. We just do a LEFT JOIN which on the Customers table. A LEFT JOIN returns every row in the first table along with any matched records in the second. Not every single record in the first will have a match but if it doesn't, it will still be in the joined table. That means a LEFT JOIN is perfect for figuring out which records are in the first table but not the second.