The SQL LEFT JOIN (or LEFT OUTER JOIN) is used to combine rows from two or more tables based on a related column, but it returns all rows from the left table (the first table), and the matching rows from the right table (the second table). If there is no match, the result is NULL for columns from the right table.
Syntax:
SELECT column1, column2, ...
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
- table1: The left table from which all rows will be returned.
- table2: The right table from which matching rows will be returned.
- column1, column2, ...: Columns to be selected from both tables.
- ON table1.column = table2.column: The condition that specifies the relationship between the two tables.
Example:
Assume we have two tables:
Employees
| EmpID | EmpName | DeptID |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
| 3 | Charlie | 30 |
Departments
| DeptID | DeptName |
|---|---|
| 10 | HR |
| 20 | Engineering |
A LEFT JOIN between these tables could look like this:
SELECT Employees.EmpName, Departments.DeptName
FROM Employees
LEFT JOIN Departments
ON Employees.DeptID = Departments.DeptID;
Result:
| EmpName | DeptName |
|---|---|
| Alice | HR |
| Bob | Engineering |
| Charlie | NULL |
In this example, the LEFT JOIN returns all employees, even those who don't have a department (like Charlie). Since Charlie doesn't have a matching DeptID in the Departments table, the result is NULL for the DeptName.
No comments:
Post a Comment