SQL Joins

SQL JOIN

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.


Different Types of SQL JOINs

Here are the different types of JOINs in SQL:

!SQL Join Types Diagram


Demo Database

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.


Basic JOIN Syntax

The general idea is to select columns from multiple tables and specify the join condition in the ON clause.

Basic INNER JOIN

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.