Quick Reference
The JOIN keyword is used in an INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN to return matching rows from two tables.
INNER JOIN
The INNER JOIN keywords returns rows that have matching values in both tables.
The following returns all orders that have customer information.
SELECT Orders.order_id, Customers.last_name, Customers.first_name
FROM Orders
INNER JOIN Customers ON Orders.customer_id = Customers.customer_id;
Note
The INNER JOIN keywords 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 the Customers table, these orders will not be shown.
LEFT JOIN
The LEFT JOIN keywords return all rows from the left table, and the matching rows from the right table. The result is NULL from the right side if there is no match.
The following returns all customers and any orders they may have.
SELECT Customers.last_name, Customers.first_name, Orders.order_id
FROM Customers
LEFT JOIN Orders ON Customers.customer_id = Orders.customer_id
ORDER BY Customers.last_name;
Note
The LEFT JOIN keywords selects all records from the left table, even if there are no matches in the right table.
RIGHT JOIN
The RIGHT JOIN keywords returns all rows from the right table, and the matching rows from the left table. The result is NULL from the left side if there is no match.
The following returns all employees and any orders they may have.
SELECT Orders.order_id, Employees.last_name, Employees.first_name
FROM Orders
RIGHT JOIN Employees ON Orders.employee_id = Employees.employee_id
ORDER BY Orders.order_id;
Note
The RIGHT JOIN keywords returns all records from the right table, even if there are no matches in the left table.
FULL OUTER JOIN
The FULL OUTER JOIN keyword returns all rows when there is a match in either the left table or right table. The returns selects all customers and all orders.
SELECT Customers.last_name, Customers.first_name, Orders.order_id
FROM Customers
FULL OUTER JOIN Orders ON Customers.customer_id = Orders.customer_id
ORDER BY Customers.last_name;
Note
The FULL OUTER JOIN keywords returns all the rows from the Customers table, and all the rows from the Orders table. If there are rows in either table that do not have matches in the other table, those rows will be listed as well.
SQL Notes:
- Any work being done to modify the structure of a database or delete tables or the the database itself should only be done after making a recent backup
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.