✏️ Explanatory Question

What is a JOIN and what are the different types of JOINs in MySQL?

👁 4 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Section 5: Joins & Relationships

35

What is a JOIN and what are the different types of JOINs in MySQL?

Level: Intermediate — One of the most heavily tested topics in any SQL interview.

A JOIN combines rows from two or more tables based on a related column between them (usually a primary key–foreign key relationship). Joins are what make relational databases so powerful.

The Main Types of JOINs

  • INNER JOIN: Returns only the rows that have matching values in both tables.
  • LEFT JOIN (LEFT OUTER): Returns all rows from the left table + matched rows from the right (NULLs where no match).
  • RIGHT JOIN (RIGHT OUTER): Returns all rows from the right table + matched rows from the left.
  • CROSS JOIN: Returns the Cartesian product — every row of the first table combined with every row of the second.
  • SELF JOIN: A table joined to itself (used for hierarchical data like employee–manager).
Important: MySQL does not support a native FULL OUTER JOIN. You simulate it by combining a LEFT JOIN and a RIGHT JOIN with UNION (covered in the next question).

JOIN Types at a Glance

JOIN Type Returns Unmatched Rows
INNER JOIN Only matching rows Excluded
LEFT JOIN All left + matches Right side = NULL
RIGHT JOIN All right + matches Left side = NULL
CROSS JOIN All combinations N/A
SELF JOIN Table joined to itself Depends on join type

Quick Example

-- Sample tables
-- employees(emp_id, name, dept_id)
-- departments(dept_id, dept_name)

-- INNER JOIN: employees who belong to a department
SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.dept_id;

-- LEFT JOIN: ALL employees, even those without a department
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id;

-- RIGHT JOIN: ALL departments, even those with no employees
SELECT e.name, d.dept_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;

-- CROSS JOIN: every employee paired with every department
SELECT e.name, d.dept_name
FROM employees e
CROSS JOIN departments d;
Interviewer tip: Name the five join types, then emphasize the difference between INNER (matches only) and OUTER joins (keep unmatched rows as NULL). Bonus: mention MySQL has no native FULL OUTER JOIN.