Brightlane's customer success team needs a list of every registered customer alongside any orders they have placed. Customers who have not yet placed any orders must still appear in the list.
Write a query to return each customer's name, order ID, and order total. Order columns will be missing for customers who have placed no orders.
Assumptions:
- The
customerstable contains every customer Brightlane has on file. - The
orderstable contains every order;customer_idon each order points to a customer. - Some customers have placed no orders. Those customers must still appear in the result, with the order columns missing.
Output:
- One row per customer-order pair, plus one row per customer with no orders, with columns
name,order_id, andtotal_amount. Order columns will be missing for customers with no orders.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
c.name,
o.id AS order_id,
o.total_amount
FROM
customers c
LEFT JOIN orders o ON c.id = o.customer_id The shape
customers is the anchor — every customer has to appear, with or without an order. A LEFT JOIN to orders keeps every left-side row and fills the order columns with NULL for the eight customers who have placed none.
Clause by clause
SELECT c.name, o.id AS order_id, o.total_amountreturns the customer's name from the left table, the order ID aliased to a domain-readable header, and the order total. For customers with no orders, the twoo.*columns come back asNULL.FROM customers cis the left table — the anchor. One row minimum per customer, regardless of order history.LEFT JOIN orders o ON c.id = o.customer_idpairs each customer with every order they have placed. Customers with multiple orders show up once per order; customers with no orders still appear once, withNULLon the right-table columns. ThatNULLis the load-bearing fact — it's how an unmatched left row signals "no match found."
Why this and not INNER JOIN
INNER JOIN would only return matched customer-order pairs. The eight customers with no orders — Omar Jensen, Mark Hayes, Nina Irwin, and the rest — would disappear silently. Customer success explicitly needs those eight in the list; they're the prospects for re-engagement. LEFT JOIN is the join that admits unmatched left rows, and the NULL in order_id is what makes them identifiable in the output.
You practiced a LEFT JOIN to preserve every row from the left table. The recurring shape: when the report's row set is anchored on the left table ("every customer") and the right table only enriches it, LEFT JOIN keeps the unmatched left rows and fills the right-table columns with NULL.