๐ Question 8: Find Customers Who Have Never Placed an Order
Suppose you have two tables:
Customers
customer_id | customer_name
------------|--------------
1 | Amit
2 | Rahul
3 | Priya
4 | Neha
5 | Raj
Orders
order_id | customer_id
---------|------------
101 | 1
102 | 3
103 | 1
104 | 5
โ Find all customers who have never placed an order.
๐ก Approach
We need to find customers from the "Customers" table who do not have a matching record in the "Orders" table.
A "LEFT JOIN" is a common and interview-friendly approach.
๐ SQL Solution
SELECT
c.customer_id,
c.customer_name
FROM Customers c
LEFT JOIN Orders o
ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;
๐ How does it work?
"LEFT JOIN" keeps every customer, even if they don't have an order.
For customers without an order, the columns from "Orders" become "NULL".
Then:
WHERE o.customer_id IS NULL
keeps only those customers.
๐ Expected Result:
customer_id | customer_name
------------|--------------
2 | Rahul
4 | Neha
โ ๏ธ Interview Trap
You can also solve this using "NOT EXISTS":
SELECT
c.customer_id,
c.customer_name
FROM Customers c
WHERE NOT EXISTS (
SELECT 1
FROM Orders o
WHERE o.customer_id = c.customer_id
);
"NOT EXISTS" is often preferred when you specifically want to test whether a matching row exists.
Be careful with "NOT IN" when NULL values can exist in the subquery, because NULL can lead to unexpected results.
๐ฏ Double Tap โค๏ธ For More