SQL Server INNER JOIN
,
LEFT JOIN
(or LEFT OUTER JOIN
), RIGHT JOIN
(or
RIGHT OUTER JOIN
), and FULL OUTER JOIN
are
different types of joins used to combine rows from multiple tables based on a related column between them. Here's a summary of each type of join and their differences:
INNER JOIN:
- Returns rows from both tables where there is a match based on the join condition.
- If there is no match between the tables based on the join condition, the row will not appear in the result set.
SELECT columns
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
LEFT JOIN (LEFT OUTER JOIN):
- Returns all rows from the left table (
table1
), and the matched rows from the right table (table2
). - If there is no match for a row in
table1
, the result will contain NULL values for columns fromtable2
.
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
RIGHT JOIN (RIGHT OUTER JOIN):
- Returns all rows from the right table (
table2
), and the matched rows from the left table (table1
). - If there is no match for a row in
table2
, the result will contain NULL values for columns fromtable1
.
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
FULL OUTER JOIN:
- Returns all rows from both tables (
table1
andtable2
), with NULL values where there is no match based on the join condition. - If there is a match, the result will contain the matched rows from both tables.
SELECT columns
FROM table1
FULL OUTER JOIN table2 ON table1.column = table2.column;
Key Differences:
Matching Behavior:
- INNER JOIN only returns rows where there is a match based on the join condition.
- LEFT JOIN and RIGHT JOIN return unmatched rows from one table (left or right respectively) with NULLs for columns from the other table.
- FULL OUTER JOIN returns all rows from both tables, combining unmatched rows with NULLs where there is no match.
Resulting Rows:
- INNER JOIN typically returns fewer rows than either table individually, as it requires a match.
- LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN return at least as many rows as the left, right, or both tables, respectively.
NULL Values:
- LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN can result in NULL values for columns from the non-matching table.
These join types allow you to control how tables are combined based on relationships defined by matching columns, providing flexibility in querying and retrieving data from multiple tables in SQL Server and other relational database systems.
Read more
Why do you use SQL Command and Queries in SQL Server?
Write a query to retrieve the total number of employees in each department.
write a query to n-th highest salary.
CURSOR AND TRIGGER IN SQL SERVER
Use of IN Operator in Sql Server
Leave Comment