SQL Joins
SQL Joins
❮ PreviousNext ❯
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
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:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
Try it Yourself »
OrderID CustomerName
SELECT *
FROM Orders
LEFT JOIN Customers
ON Orders.CustomerIDCustomers.CustomerID
= ;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18
10309 37 3 1996-09-19
10310 77 8 1996-09-20
And a selection from the "Customers" table:
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Try it Yourself »
Note: The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns. If there are records in the "Orders"
table that do not have matches in "Customers", these orders will not be
shown!
Try it Yourself »
Exercise:
Choose the correct JOIN clause to select all records from the two tables where
there is a match in both tables.
SELECT *
FROM Orders
inner join customers
ON Orders.CustomerID=Customers.CustomerID;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10309 37 3 1996-09-19
10310 77 8 1996-09-20
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Try it Yourself »
Note: The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18
10309 37 3 1996-09-19
10310 77 8 1996-09-20
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Try it Yourself »
Note: The RIGHT JOIN keyword returns all records from the right table
(Employees), even if there are no matches in the left table (Orders).
Exercise:
Choose the correct JOIN clause to select all the records from
the Customers table plus all the matches in the Orders table.
SELECT *
FROM Orders
right join customers
ON Orders.CustomerID=Customers.CustomerID;