The JOIN operator works similarly to set operations in relational algebra.
Let’s say we have two tables: cats and candies. Each row in the cat table contains the ID of the candy that belongs to it
— candy_id.
cat table
| id |
name |
candy_id |
| 1 |
Mia |
3 |
| 2 |
Astronaut Cat’s Brother |
null |
| 3 |
Astronaut Cat |
2 |
candy table
| id |
name |
| 1 |
Plutonian Praline |
| 2 |
Explosive Comet |
| 3 |
Universal Harmony |
null
— a special value meaning «no data»; the cat with ID 2 has no candy.
Let’s build an SQL query that joins the cat and candy tables using the equality condition for the candy ID (candy_id = id) in both tables.
SELECT cat.name, candy.name -- select cat names and candy names
FROM cat -- from the cat table
JOIN candy ON cat.candy_id = candy.id; -- join with the candy table by matching the candy ID
The result of the query will be a joined table with rows merged from the
cat and candy.
Joined cat and candy table
| cat.name |
candy.name |
| Mia |
Universal Harmony |
| Astronaut Cat |
Explosive Comet |
INNER JOIN is used by default if you don’t specify additional keywords.
JOIN = INNER JOIN