A JOIN combines rows from two or more tables based on a related column.
Consider:
Employees
ID | Name | Dept_ID |
|---|---|---|
1 | Aman | 10 |
2 | Rahul | 20 |
3 | Ritesh | 30 |
4 | Karan | 10 |
Departments
Dept_ID | Department |
|---|---|
10 | IT |
20 | HR |
40 | Sales |
What is INNER JOIN?
Returns only matching rows from both tables.
SELECT e.Name, d.Department
FROM Employees e
INNER JOIN Departments d
ON e.Dept_ID = d.Dept_ID;Result:
Name | Department |
|---|---|
Aman | IT |
Rahul | HR |
Karan | IT |
What is LEFT JOIN?
Returns all rows from the left table and matching rows from the right table.
If there is no match, right-side columns contain NULL.
SELECT e.Name, d.Department
FROM Employees e
LEFT JOIN Departments d
ON e.Dept_ID = d.Dept_ID;Ritesh will appear with NULL as the department.
What is RIGHT JOIN?
Returns all rows from the right table and matching rows from the left table.
SELECT e.Name, d.Department
FROM Employees e
RIGHT JOIN Departments d
ON e.Dept_ID = d.Dept_ID;Sales will appear with NULL for employee details.
What is FULL OUTER JOIN?
Returns all matching and non-matching rows from both tables, filling missing sides with NULL.
SELECT e.Name, d.Department
FROM Employees e
FULL OUTER JOIN Departments d
ON e.Dept_ID = d.Dept_ID;What is CROSS JOIN?
Returns the Cartesian product of two tables.
If table A has 3 rows and table B has 4 rows, CROSS JOIN returns 12 rows.
What is SELF JOIN?
A table is joined with itself.
Example: Finding employees and their managers.
SELECT e.Name AS Employee,
m.Name AS Manager
FROM Employees e
LEFT JOIN Employees m
ON e.Manager_ID = m.ID;