Customers Who Never Order - Problem
Imagine you're running a business and want to identify inactive customers who might need a marketing push! ๐
You have two database tables:
| Customers Table | |
|---|---|
| id (int) | name (varchar) |
| Each row contains a customer's ID and name | |
| Orders Table | |
|---|---|
| id (int) | customerId (int) |
| Each row contains an order ID and the customer who placed it | |
Your mission: Write a SQL query to find all customers who have never placed an order. These are potential customers you could target with special promotions!
The result should return customer names in any order.
Example:
If Alice and Bob are in the Customers table, but only Alice has orders in the Orders table, then Bob should be returned as he never ordered anything.
Input & Output
example_1.sql โ Basic Example
$
Input:
Customers: [(1,'Alice'), (2,'Bob'), (3,'Charlie')]\nOrders: [(101,1), (102,1), (103,3)]
โบ
Output:
[('Bob')]
๐ก Note:
Alice has orders 101 and 102, Charlie has order 103, but Bob has no orders, so only Bob is returned.
example_2.sql โ All Customers Have Orders
$
Input:
Customers: [(1,'Alice'), (2,'Bob')]\nOrders: [(101,1), (102,2)]
โบ
Output:
[]
๐ก Note:
Both Alice and Bob have at least one order, so no customers are returned.
example_3.sql โ No Orders Table
$
Input:
Customers: [(1,'Alice'), (2,'Bob'), (3,'Charlie')]\nOrders: []
โบ
Output:
[('Alice'), ('Bob'), ('Charlie')]
๐ก Note:
No orders exist, so all customers are returned as they have never ordered anything.
Visualization
Tap to expand
Understanding the Visualization
1
Customer Registry
You have a list of all customers who signed up for your loyalty program
2
Purchase History
You also have records of all purchases made by customer ID
3
LEFT JOIN Magic
Connect each customer to their purchases, but keep customers even if they have no purchases
4
Find the Gaps
Customers with NULL purchase records are the ones who never bought anything
Key Takeaway
๐ฏ Key Insight: LEFT JOIN preserves all customers while identifying those without orders through NULL values - it's like keeping everyone on the guest list but highlighting who didn't show up to the party!
Time & Space Complexity
Time Complexity
O(n ร m)
For each of n customers, we potentially scan m orders
โ Linear Growth
Space Complexity
O(1)
No additional space needed beyond result set
โ Linear Space
Constraints
- 1 โค customers.length โค 104
- 1 โค orders.length โค 106
- Customer IDs are unique in Customers table
- Order IDs are unique in Orders table
- customerId in Orders table references id in Customers table
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code