Answer to SQL Leetcode Question 183. Customers Who Never Order

Answer to SQL Leetcode Question 183

183Customers Who Never Order 

Table: Customers

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
+-------------+---------+
id is the primary key column for this table.
Each row of this table indicates the ID and name of a customer.

 

Table: Orders

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| customerId  | int  |
+-------------+------+
id is the primary key column for this table.
customerId is a foreign key of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.

 

Write an SQL query to report all customers who never order anything.

Return the result table in any order.

The query result format is in the following example.

 

Example 1:

Input: 
Customers table:
+----+-------+
| id | name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+
Output: 
+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

Solution :

# Write your MySQL query statement below
SELECT c.name as Customers
FROM Customers c
Left Join Orders o
On c.id = o.customerId
where o.customerId is null

Approach :
Our table needs to include all the Customers from Customer table, which led to using LEFT JOIN. Further customers with null values of customerId shows the customer who never order, which is filtered out by WHERE clause.

Happy Learning!

Comments

Popular posts from this blog

SQL for beginners : finding out Employees Earning More Than Their Managers

SQL Medium difficulty practice question : Consecutive Numbers