Sponsored
Sponsored
The goal is to find customers who never made an order. By using a LEFT JOIN between the Customers and Orders tables, we can identify which customer IDs do not appear in the Orders table. We will check for NULL entries in the Orders table after the join to find these customers.
Time Complexity: O(n), where n is the number of rows in the Customers table.
Space Complexity: O(n), primarily for storing the result set.
1SELECT Customers.name AS Customers FROM Customers LEFT JOIN Orders ON Customers.id = Orders.customerId WHERE Orders.customerId IS NULL;
The SQL query performs a LEFT JOIN between the Customers
table and the Orders
table on the customer ID. A LEFT JOIN ensures that all records from the left (Customers) table are returned, along with matching records from the right (Orders) table where they exist. If there is no match, the result is NULL on the right side. We filter those results where the Orders.customerId
is NULL
, implying that there are no orders for those customers.
This approach uses a subquery to first identify the list of customers who have placed orders. Then, it excludes these customers from the list of all customers to find those who haven't placed any orders.
Time Complexity: O(n + m), with n as the number of customers and m as the number of orders.
Space Complexity: O(1) for the operation itself, but the result set storage would be O(k), where k is the number of customers who have never ordered.
1customers = {1: 'Joe', 2: 'Henry', 3: 'Sam', 4: 'Max'}
2orders = {1: 3, 2: 1}
3
4customers_set = set(customers.keys())
5orders_set = set(orders.values())
never_ordered = [customers[cust_id] for cust_id in (customers_set - orders_set)]
print(never_ordered) # Output: ['Henry', 'Max']
This Python solution uses basic set operations. It initializes two sets: one with all customer IDs and another with IDs that have placed orders. By taking the difference of these sets, we identify customer IDs that never appear in orders. We then map these IDs back to their corresponding names.