SQL JOIN

The SQL JOIN clause is used to combine rows from two or more tables based on a related column. This is essential for retrieving data from multiple tables in a relational database, enabling meaningful associations between data sets.

The most common types of joins are: INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, and CROSS JOIN. These joins define how rows from the tables are matched and included in the result.

Tables Used

Orders Table:
OrderID Product CustomerID
1 Laptop 101
2 Phone 102
3 Tablet NULL
Customers Table:
CustomerID CustomerName
101 Alice
102 Bob

Example

We’ll perform an INNER JOIN to find all orders placed by customers listed in the database. This query combines data from the Orders and Customers tables based on the CustomerID column.

Code Example


-- Perform an INNER JOIN between Orders and Customers
SELECT Orders.OrderID, Orders.Product, Customers.CustomerName
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;

-- View the resulting table
            

Output Table

OrderID Product CustomerName
1 Laptop Alice
2 Phone Bob

Explanation

- The INNER JOIN retrieves rows where there is a match between the CustomerID column in both tables.
- Only orders placed by customers in the Customers table are displayed.
- The resulting table combines relevant columns from both tables.