Bird
0
0

You want to list all customers and their last order date if any. Which query correctly uses LEFT JOIN to achieve this?

hard📝 Application Q15 of 15
SQL - LEFT and RIGHT JOIN
You want to list all customers and their last order date if any. Which query correctly uses LEFT JOIN to achieve this?
Customers(id, name)
Orders(id, customer_id, order_date)
ASELECT c.name, MAX(o.order_date) FROM Customers c LEFT JOIN Orders o ON c.id = o.customer_id GROUP BY c.name;
BSELECT c.name, o.order_date FROM Customers c LEFT JOIN Orders o ON c.id = o.customer_id WHERE o.order_date = (SELECT MAX(order_date) FROM Orders);
CSELECT c.name, o.order_date FROM Customers c INNER JOIN Orders o ON c.id = o.customer_id;
DSELECT c.name, MAX(o.order_date) FROM Customers c INNER JOIN Orders o ON c.id = o.customer_id GROUP BY c.name;
Step-by-Step Solution
Solution:
  1. Step 1: Understand requirement for all customers

    We want all customers listed, even those without orders, so LEFT JOIN is needed.
  2. Step 2: Aggregate last order date per customer

    Using MAX(o.order_date) with GROUP BY c.name gives last order date or NULL if no orders.
  3. Step 3: Check options

    SELECT c.name, MAX(o.order_date) FROM Customers c LEFT JOIN Orders o ON c.id = o.customer_id GROUP BY c.name; uses LEFT JOIN and GROUP BY correctly. SELECT c.name, o.order_date FROM Customers c LEFT JOIN Orders o ON c.id = o.customer_id WHERE o.order_date = (SELECT MAX(order_date) FROM Orders); filters in WHERE, excluding customers without orders. Options A and C use INNER JOIN, excluding customers without orders.
  4. Final Answer:

    SELECT c.name, MAX(o.order_date) FROM Customers c LEFT JOIN Orders o ON c.id = o.customer_id GROUP BY c.name; -> Option A
  5. Quick Check:

    LEFT JOIN + GROUP BY + MAX gets last order date including customers without orders [OK]
Quick Trick: Use LEFT JOIN with GROUP BY and MAX to include all left rows [OK]
Common Mistakes:
MISTAKES
  • Using INNER JOIN excludes customers without orders
  • Filtering right table in WHERE removes unmatched rows
  • Not grouping when using aggregate functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes