Lessons › SQL › Chapter 5: Joins, subqueries and CTEs
SQL lesson
LEFT JOIN
A LEFT JOIN takes two tables and sticks them together side by side. It always keeps every row from the left table, no matter what. The first table you write (orders) is the left table. The second (customers) is the right table. For each order, SQL looks for a match. If there's one, it adds the customer columns. If not, those columns are empty.
Try this lesson free →Example
Keeping All Retail Orders with LEFT JOIN
SELECT *
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id| order_id | customer_id | revenue | customer_id | full_name |
|---|---|---|---|---|
| O2001 | C101 | 129.99 | C101 | Alice Chen |
| O2002 | C102 | 54.5 | C102 | Bob Tanaka |
| O2003 | C109 | 310.0 | NULL | NULL |
Step by step
- Your main table. It's written first, so SQL calls it the left table. Every order stays.
SELECT * FROM orders - The extra table. It's written second, so SQL calls it the right table. If an order has no match, its extra columns are empty.
SELECT * FROM orders LEFT JOIN customers - Both tables have a customer_id column. SQL uses it to match each order to its customer. Writing orders. in front just means 'the customer_id in orders'.
SELECT * FROM orders LEFT JOIN customers ON orders.customer_id = customers.customer_id;
Practice
1. Using orders and customers, show every column. Keep every order, even ones with no matching customer.
SELECT * FROM orders LEFT JOIN customers ON orders.customer_id = customers.customer_id2. Using orders and customers, show order_id, revenue and full_name. Keep every order, even ones with no matching customer.
SELECT o.order_id, o.revenue, c.full_name FROM orders o LEFT JOIN customers c ON o.customer_id = c.customer_id3. Using products and reviews, show every column. Keep every product, even ones with no review.
SELECT * FROM products LEFT JOIN reviews ON products.product_id = reviews.product_id4. Using orders and shipments, show every column. Keep every order, even ones that haven't shipped.
SELECT * FROM orders LEFT JOIN shipments ON orders.order_id = shipments.order_id5. Using suppliers and supplier_products, show every column. Keep every supplier, even ones with no products listed.
SELECT * FROM suppliers LEFT JOIN supplier_products ON suppliers.supplier_id = supplier_products.supplier_idLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →