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 →Example
Matching Retail Orders to Customers with INNER JOIN
SELECT *
FROM orders
INNER 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 |
Step by step
- Your main table. It's written first, so SQL calls it the left table.
SELECT * FROM orders - 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 - 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
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_id2. 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_id3. 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_id4. 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_id5. 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_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 →