BBampaa

Lessons › SQL › Chapter 5: Joins, subqueries and CTEs

SQL lesson

INNER JOIN

An INNER JOIN takes two tables and sticks them together side by side. It only keeps rows that have a match in both tables. The first table you write (orders) is the left table. The second (customers) is the right table. For each order, SQL looks for a customer with the same customer_id. If there's one, they go on one row. If not, the order is left out.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Matching Retail Orders to Customers with INNER JOIN

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

Result:

order_idcustomer_idrevenuecustomer_idfull_name
O2001C101129.99C101Alice Chen
O2002C10254.5C102Bob Tanaka

Step by step

  1. Your main table. It's written first, so SQL calls it the left table.
    SELECT *
    FROM orders
  2. The extra table. It's written second, so SQL calls it the right table. Only orders with a match stay.
    SELECT *
    FROM orders
    INNER 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
    INNER 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 only orders that have a matching customer.
SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id
2. Using orders and customers, show order_id, revenue and full_name. Keep only orders that have a matching customer.
SELECT orders.order_id, orders.revenue, customers.full_name FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id
3. Using products and reviews, show every column. Keep only products that have a review.
SELECT * FROM products INNER JOIN reviews ON products.product_id = reviews.product_id
4. Using orders and shipments, show every column. Keep only orders that have shipped.
SELECT * FROM orders INNER JOIN shipments ON orders.order_id = shipments.order_id
5. Using suppliers and supplier_products, show every column. Keep only suppliers that have products listed.
SELECT * FROM suppliers INNER 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