SQL JOIN Types
SQL JOIN is used to combine records from two or more tables in a database based on related
columns.
1. INNER JOIN
Returns only the rows that have matching values in both tables.
Example:
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
2. LEFT JOIN (LEFT OUTER JOIN)
Returns all rows from the left table, and the matched rows from the right table. If there is no
match, the result is NULL from the right side.
Example:
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id;
3. RIGHT JOIN (RIGHT OUTER JOIN)
Returns all rows from the right table, and the matched rows from the left table. If there is no
match, the result is NULL from the left side.
Example:
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id;
4. FULL JOIN (FULL OUTER JOIN)
Returns all records when there is a match in either left or right table. If there is no match,
the result is NULL on the side that doesn't have a match.
Example:
SELECT employees.name, departments.department_name
FROM employees
FULL OUTER JOIN departments ON employees.department_id = departments.id;
5. CROSS JOIN
Returns the Cartesian product of the two tables. Every row from the first table is joined with
all rows from the second table.
Example:
SELECT employees.name, departments.department_name
FROM employees
CROSS JOIN departments;
6. SELF JOIN
A self join is a regular join but the table is joined with itself.
Example:
SELECT A.name AS Employee, B.name AS Manager
FROM employees A
JOIN employees B ON A.manager_id = B.id;