BBampaa

Lessons › SQL › Chapter 5: Combining tables

SQL lesson

INNER JOIN

INNER JOIN combines rows from two tables by finding records that match on both sides, silently leaving out anything that has no partner.

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

Example

Matching Retail Orders to Customers with INNER JOIN

SELECT o.order_id, o.revenue, c.region, c.channel
FROM orders o
INNER JOIN customers c
  ON o.customer_id = c.customer_id

Result:

order_idrevenueregionchannel
O2001129.99NortheastOnline
O200254.5SoutheastMobile
O2003310.0WestOnline
O200489.75MidwestIn-Store

Step by step

  1. After SELECT, list the column names you want, separated by commas.
    SELECT o.order_id, o.revenue, c.region, c.channel
  2. FROM tells SQL which table to pull the data from.
    SELECT o.order_id, o.revenue, c.region, c.channel
    FROM orders o
  3. INNER JOIN returns rows that match in both tables.
    SELECT o.order_id, o.revenue, c.region, c.channel
    FROM orders o
    INNER JOIN customers c
      ON o.customer_id = c.customer_id;

Practice

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

1. Write a query that combines orders and customers on the customer_id column, returning only matching rows.
SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id
2. Join orders and returns on order_id to see which orders have been returned, keeping only matching rows.
SELECT * FROM orders INNER JOIN returns ON orders.order_id = returns.order_id
3. Look at the products and reviews tables above. Find the column they share and write a query that joins them on it, returning only matching rows.
SELECT * FROM products INNER JOIN reviews ON products.product_id = reviews.product_id
4. Examine the orders and shipments tables. Identify the column they have in common and write an INNER JOIN using that column.
SELECT * FROM orders INNER JOIN shipments ON orders.order_id = shipments.order_id
5. Look at the suppliers and supplier_products tables. Find the column they share and use it to write an INNER JOIN between them.
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