MySQL Joins - Interview Guide
Definition
In MySQL, a JOIN is used to combine rows from two or more tables based on a related column (usually a
foreign key).
Types of Joins in MySQL
1. INNER JOIN: Returns only matching rows between tables.
2. LEFT JOIN: Returns all rows from the left table, with matching rows from the right table.
3. RIGHT JOIN: Returns all rows from the right table, with matching rows from the left table.
4. FULL JOIN: Returns all rows when there is a match in either table (not supported directly in MySQL).
5. SELF JOIN: A table joins with itself.
6. CROSS JOIN: Returns Cartesian product - all combinations of rows.
1. INNER JOIN
Returns only rows with matching keys in both tables.
Example:
SELECT employees.name, departments.dept_name
FROM employees
INNER JOIN departments
ON employees.dept_id = departments.dept_id;
2. LEFT JOIN (LEFT OUTER JOIN)
Returns all rows from the left table, even if there's no match in the right.
Example:
SELECT employees.name, departments.dept_name
FROM employees
LEFT JOIN departments
ON employees.dept_id = departments.dept_id;
MySQL Joins - Interview Guide
3. RIGHT JOIN (RIGHT OUTER JOIN)
Returns all rows from the right table, even if there's no match in the left.
Example:
SELECT employees.name, departments.dept_name
FROM employees
RIGHT JOIN departments
ON employees.dept_id = departments.dept_id;
4. FULL JOIN (Using UNION)
Returns all records when there is a match in either left or right table.
Example:
SELECT employees.name, departments.dept_name
FROM employees
LEFT JOIN departments
ON employees.dept_id = departments.dept_id
UNION
SELECT employees.name, departments.dept_name
FROM employees
RIGHT JOIN departments
ON employees.dept_id = departments.dept_id;
5. SELF JOIN
A table is joined with itself, often used for hierarchical data.
Example:
SELECT A.name AS Employee, B.name AS Manager
FROM employees A
JOIN employees B
MySQL Joins - Interview Guide
ON A.manager_id = B.id;
6. CROSS JOIN
Returns all possible combinations of rows from both tables.
Example:
SELECT employees.name, departments.dept_name
FROM employees
CROSS JOIN departments;
Interview Tips
- INNER JOIN is the most commonly used.
- Use LEFT JOIN when you want all records from one table regardless of matches.
- FULL JOIN is simulated with UNION in MySQL.
- Use small examples like employees and departments to explain clearly.