025 SQL Joins
The current W3Schools page explains SQL Joins. Here’s a summary:
-
Purpose of SQL Joins:
Joins are used to combine rows from two or more tables based on a related column between them. -
Example Tables:
The Orders table contains columns like OrderID, CustomerID, and OrderDate.
The Customers table includes CustomerID, CustomerName, ContactName, and Country.
The common column "CustomerID" relates the two tables. -
Sample SQL JOIN Query:
Uses INNER JOIN:SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID; -
Types of SQL JOINs:
- (INNER) JOIN: Returns records with matching values in both tables.
- LEFT (OUTER) JOIN: Returns all records from the left table and matched records from the right table.
- RIGHT (OUTER) JOIN: Returns all records from the right table and matched records from the left.
- FULL (OUTER) JOIN: Returns all records with a match in either left or right table.
-
Key takeaway:
The main purpose of an SQL JOIN is to combine rows from two or more tables based on a related column.[1]
SQLÂ Joins
SQL JOIN
AÂ JOINÂ clause is used to combine rows from two or more tables, based on a related column between them.
Let's look at a selection from the "Orders" table:
| OrderID | CustomerID | OrderDate |
|---|---|---|
| 10308 | 2 | 1996-09-18 |
| 10309 | 37 | 1996-09-19 |
| 10310 | 77 | 1996-09-20 |
Then, look at a selection from the "Customers" table:
| CustomerID | CustomerName | ContactName | Country |
|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Germany |
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Mexico |
| 3 | Antonio Moreno TaquerÃa | Antonio Moreno | Mexico |
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have matching values in both tables:
SELECTÂ Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROMÂ Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:
| OrderID | CustomerName | OrderDate |
|---|---|---|
| 10308 | Ana Trujillo Emparedados y helados | 9/18/1996 |
| 10365 | Antonio Moreno TaquerÃa | 11/27/1996 |
| 10383 | Around the Horn | 12/16/1996 |
| 10355 | Around the Horn | 11/15/1996 |
| 10278 | Berglunds snabbköp | 8/12/1996 |
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tablesLEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right tableRIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left tableFULL (OUTER) JOIN: Returns all records when there is a match in either left or right table