T-SQL JOIN Clause

The JOIN clause is used to combine rows from two or more tables based on a related column between them. This is fundamental for retrieving data that spans across multiple database tables.

Types of JOINs

SQL Server supports several types of JOIN operations:

INNER JOIN

Returns only the rows where the join condition is met in both tables. This is the most common type of join.

SELECT
    column1,
    column2,
    ...
FROM
    table1
INNER JOIN
    table2 ON table1.common_column = table2.common_column;

LEFT JOIN (or LEFT OUTER JOIN)

Returns all rows from the left table, and the matched rows from the right table. If there is no match, the result is NULL on the right side.

SELECT
    column1,
    column2,
    ...
FROM
    table1
LEFT JOIN
    table2 ON table1.common_column = table2.common_column;

RIGHT JOIN (or RIGHT OUTER JOIN)

Returns all rows from the right table, and the matched rows from the left table. If there is no match, the result is NULL on the left side.

SELECT
    column1,
    column2,
    ...
FROM
    table1
RIGHT JOIN
    table2 ON table1.common_column = table2.common_column;

FULL JOIN (or FULL OUTER JOIN)

Returns all rows when there is a match in either the left or the right table. If there is no match, NULL values are returned for columns of the table that does not have a match.

SELECT
    column1,
    column2,
    ...
FROM
    table1
FULL JOIN
    table2 ON table1.common_column = table2.common_column;

CROSS JOIN

Returns the Cartesian product of the two tables. This means it pairs every row from the first table with every row from the second table. Use this with caution, as it can produce very large result sets.

SELECT
    column1,
    column2,
    ...
FROM
    table1
CROSS JOIN
    table2;

Self-JOIN

A self-JOIN is a regular JOIN, but the table is joined with itself. This is typically used when the table contains hierarchical data or when you need to compare rows within the same table.

Example: Joining Employee and Department Tables

Let's say we have two tables: Employees and Departments.

Employees table:

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    DepartmentID INT
);

Departments table:

CREATE TABLE Departments (
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(50)
);

To get a list of employees and their department names, we can use an INNER JOIN:

SELECT
    e.FirstName,
    e.LastName,
    d.DepartmentName
FROM
    Employees AS e
INNER JOIN
    Departments AS d ON e.DepartmentID = d.DepartmentID;

This query will return only employees who are assigned to a valid department present in the Departments table.

Key Considerations

Mastering the JOIN clause is essential for effective data retrieval and manipulation in SQL Server.