SQL Joins are used to combine rows from two or more tables based on a related column between them. Joins allow you to retrieve data from multiple tables in a single query, making it easier to work with complex datasets.
There are several types of joins in SQL, including:
Here’s an example of how to use an INNER JOIN to retrieve data from two tables:
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
This query retrieves the first name and last name of employees along with their respective department names by matching the DepartmentID
in both tables.
To retrieve all employees along with their department names (including those without a department), you can use a LEFT JOIN:
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
This query returns all employees, and if an employee does not belong to any department, the DepartmentName
will show as NULL.
Try creating your own queries using different types of joins. Here’s a hint for a FULL JOIN:
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName
FROM Employees
FULL OUTER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;