Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

JOIN

INNER JOIN

The INNER JOIN command retrieves rows with matching values in both tables.

The following SQL selects all orders along with corresponding customer information:

Example

SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID; 

Please note that the INNER JOIN keyword selects all rows from both tables only if there is a match between the columns. Orders without corresponding customers will not be displayed.

The following SQL statement selects all orders along with customer and shipper information:

Example

SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID); 

LEFT JOIN

The LEFT JOIN command retrieves all rows from the left table and the matching rows from the right table. If there is no match, NULL values are returned from the right side. The following SQL will select all customers and any associated orders:

Example

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The LEFT JOIN keyword retrieves all records from the left table (Customers), irrespective of whether there are matches in the right table (Orders).

RIGHT JOIN

The RIGHT JOIN command fetches all rows from the right table and the matching records from the left table. If there is no match, NULL values are returned from the left side.

The following SQL will return all employees and any orders they might have placed:

Example

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID; 

Note: The RIGHT JOIN keyword retrieves all records from the right table (Employees), regardless of whether there are matches in the left table (Orders).

FULL OUTER JOIN

The FULL OUTER JOIN command retrieves all rows where there is a match in either the left or right table. 

The following SQL statement retrieves all customers and all orders:

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The FULL OUTER JOIN keyword fetches all rows from both the left table (Customers) and the right table (Orders). If there are rows in “Customers” without matches in “Orders”, or rows in “Orders” without matches in “Customers”, those rows are also included.