- Understand what an Inner Join is.
- Learn how to use Inner Joins to combine data from multiple tables.
- Practice using Inner Joins.
What is an Inner Join?
An Inner Join is used to return rows when there is a match in both tables.
Syntax
SELECT *
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name; The INNER keyword is optional, and we can also write the query as follows:
SELECT *
FROM table1
JOIN table2
ON table1.column_name = table2.column_name; Example
Imagine we have two separate tables.
The fruits table contains the following data:
| id | name |
|---|---|
| 1 | Apple |
| 2 | Banana |
And the prices table contains the following data:
| id | price |
|---|---|
| 1 | 2.5 |
| 2 | 1.5 |
We want to combine it like this:
| id | name | price |
|---|---|---|
| 1 | Apple | 2.5 |
| 2 | Banana | 1.5 |
Both tables have a column called id that can be used to join the tables.
When we use an Inner Join, we combine the data from both tables based on the id column.
In the following example, we join the fruits and prices tables on the id column.
SELECT *
FROM fruits
JOIN prices
ON fruits.id = prices.id; This will return the following result:
Output
| id | name | price |
|---|---|---|
| 1 | Apple | 2.5 |
| 2 | Banana | 1.5 |
Exercise 1.1
Run the following code to join the fruits and prices tables on the id column.
Exercise 1.2
Complete the following SQL statement to join the fruits and prices tables on the id column.
We’ve provided the SELECT statement and the FROM clause. You need to add the INNER JOIN and ON clause.
| id | name |
|---|---|
| 1 | Apple |
| 2 | Banana |
| id | price |
|---|---|
| 1 | 2.5 |
| 2 | 1.5 |
Summary
In this section, we learned about Inner Joins and how to use them to combine data from multiple tables.