Write a query to get all customers and their orders using LEFT JOIN.
Objective:
Write a SQL query to get all customers and their orders using LEFT JOIN.
That means:
- Show all customers, even if they have no orders.
- Use
LEFT JOIN
betweencustomers
andorders
tables.
Step 1: Create the Tables
We'll create two tables:
1. customers
Table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100),
city VARCHAR(50)
);
2. orders
Table
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
amount DECIMAL(10,2),
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
Step 2: Insert Dummy Data
Insert into customers
:
INSERT INTO customers (customer_id, customer_name, city) VALUES
(1, 'Alice Smith', 'New York'),
(2, 'Bob Johnson', 'Los Angeles'),
(3, 'Charlie Lee', 'Chicago'),
(4, 'Diana Patel', 'Houston');
Insert into orders
:
INSERT INTO orders (order_id, order_date, amount, customer_id) VALUES
(101, '2024-01-15', 250.00, 1),
(102, '2024-02-10', 500.00, 1),
(103, '2024-03-05', 750.00, 3),
(104, '2024-03-18', 320.00, 3);
Note: Bob (ID 2) and Diana (ID 4) do not have any orders.
Step 3: LEFT JOIN Query
SELECT
c.customer_id,
c.customer_name,
c.city,
o.order_id,
o.order_date,
o.amount
FROM
customers c
LEFT JOIN
orders o ON c.customer_id = o.customer_id;
Step 4: Output
customer_id | customer_name | city | order_id | order_date | amount |
---|---|---|---|---|---|
1 | Alice Smith | New York | 101 | 2024-01-15 | 250.00 |
1 | Alice Smith | New York | 102 | 2024-02-10 | 500.00 |
2 | Bob Johnson | Los Angeles | NULL | NULL | NULL |
3 | Charlie Lee | Chicago | 103 | 2024-03-05 | 750.00 |
3 | Charlie Lee | Chicago | 104 | 2024-03-18 | 320.00 |
4 | Diana Patel | Houston | NULL | NULL | NULL |
Explanation:
LEFT JOIN
keeps all rows fromcustomers
.- If a customer has no orders, the
order_id
,order_date
, andamount
are shown as NULL. - This is ideal for reporting customers who haven’t ordered yet.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.