BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Keeping All Retail Orders with LEFT JOIN

SELECT *
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id

Result:

order_idcustomer_idrevenuecustomer_idfull_name
O2001C101129.99C101Alice Chen
O2002C10254.5C102Bob Tanaka
O2003C109310.0NULLNULL

Step by step

  1. Your main table. It's written first, so SQL calls it the left table. Every order stays.
    SELECT *
    FROM orders
  2. 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
  3. 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

Try each one in your head first, then open the answer.

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_id
2. 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_id
3. 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_id
4. 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_id
5. 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_id

Learn 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 →
About 5–10 minutes · no sign-up needed