Joins in SQL are used to combine rows from two or more tables based on a related column between them. In Microsoft SQL Server (MS SQL), there are several types of joins, each serving different purposes. Here’s a quick overview:
1. INNER JOIN
The INNER JOIN
keyword selects records that have matching values in both tables.
Example:
2. LEFT JOIN (or LEFT OUTER JOIN)
The LEFT JOIN
keyword returns all rows from the left table and the matched rows from the right table. The result is NULL
from the right side if there is no match.
Example:
3. RIGHT JOIN (or RIGHT OUTER JOIN)
The RIGHT JOIN
keyword returns all rows from the right table and the matched rows from the left table. The result is NULL
from the left side when there is no match.
Example:
4. FULL JOIN (or FULL OUTER JOIN)
The FULL JOIN
keyword returns all rows when there is a match in either left or right table. If there is no match, the result is NULL
on the side that does not have a match.
Example:
5. CROSS JOIN
The CROSS JOIN
keyword returns the Cartesian product of the two tables. It means every row of the first table is combined with every row of the second table.
Example:
6. SELF JOIN
A SELF JOIN
is a regular join but the table is joined with itself. This is useful for hierarchical data or comparing rows within the same table.
Example:
Key Points:
- Join Conditions: Joins typically involve comparing columns between the tables, often using primary and foreign keys.
- Performance: Be mindful of performance impacts, especially with large datasets. Proper indexing can help optimize joins.
- Aliasing: Use table aliases (like
e1
ande2
in the SELF JOIN example) to simplify queries and improve readability.