SQL joins are used to combine rows from two or more tables based on a related column between them. There are several types of joins, each serving a specific purpose.
Types of SQL Joins
INNER JOIN:
- Retrieves records that have matching values in both tables.
- Syntax:
LEFT JOIN (LEFT OUTER JOIN):
- Returns all records from the left table, and the matched records from the right table. If there's no match, the result is NULL on the right side.
- Syntax:
RIGHT JOIN (RIGHT OUTER JOIN):
- Returns all records from the right table, and the matched records from the left table. If there's no match, the result is NULL on the left side.
- Syntax:
FULL JOIN (FULL OUTER JOIN):
- Combines the result of both LEFT JOIN and RIGHT JOIN. Returns all records from both tables, with NULLs where there is no match.
- Syntax:
CROSS JOIN:
- Returns the Cartesian product of both tables, meaning each row in the first table is paired with every row in the second table.
- Syntax:
SELF JOIN:
- A join where a table is joined with itself. It can be useful for hierarchical or comparative data.
- Syntax:
Example Tables
Table: Employees
| EmployeeID | Name | DepartmentID |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
| 3 | Charlie | NULL |
Table: Departments
| DepartmentID | DepartmentName |
|---|---|
| 10 | HR |
| 20 | IT |
| 30 | Finance |
Examples of Joins
INNER JOIN Example:
Result:
Name DepartmentName Alice HR Bob IT LEFT JOIN Example:
Result:
Name DepartmentName Alice HR Bob IT Charlie NULL RIGHT JOIN Example:
Result:
Name DepartmentName Alice HR Bob IT NULL Finance FULL JOIN Example:
Result:
Name DepartmentName Alice HR Bob IT Charlie NULL NULL Finance
No comments:
Post a Comment