A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
In a relational database, data is often split across multiple tables to reduce redundancy (a process called normalization). For example, we might have a Customers table and an Orders table. The Orders table doesn't store the customer's name and address; it only stores a CustomerID that links back to the Customers table.
To get a complete view, like seeing which customer placed which order, we need to JOIN these tables together.
Here are the different types of JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables. This is the most common type of join.LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table. The result is NULL from the right side if there is no match.RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table. The result is NULL from the left side if there is no match.FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table. It combines the results of both LEFT and RIGHT joins.SELF JOIN: A regular join, but the table is joined with itself.!SQL Join Types Diagram
For the join examples, we will use the Customers and Orders tables.
Customers Table:
| CustomerID | CustomerName | Country |
|---|---|---|
| 1 | Alfreds Futterkiste | Germany |
| 2 | Ana Trujillo Emparedados | Mexico |
| 3 | Antonio Moreno Taquería | Mexico |
| 4 | Around the Horn | UK |
Orders Table:
| OrderID | CustomerID | OrderDate |
|---|---|---|
| 10308 | 2 | 1996-09-18 |
| 10309 | 37 | 1996-09-19 |
| 10310 | 77 | 1996-09-20 |
The CustomerID column in the Orders table links to the CustomerID in the Customers table.
The general idea is to select columns from multiple tables and specify the join condition in the ON clause.
SELECT Orders.OrderID, Customers.CustomerName FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
In the following chapters, we will explore each of these join types in detail.