✏️ Explanatory Question

What is the difference between UNION and JOIN?

👁 6 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

40

What is the difference between UNION and JOIN?

Level: Intermediate — A conceptual favourite; both combine data but in completely different directions.

Both combine data from multiple tables, but the direction of the combination is the key difference:

  • JOIN: Combines data horizontally — it adds columns from another table, side by side, based on a matching condition.
  • UNION: Combines data vertically — it stacks the rows of two result sets on top of each other.
Easy way to remember: JOIN makes the result wider (more columns), while UNION makes it taller (more rows).

UNION Rules

  • Each SELECT must have the same number of columns.
  • Corresponding columns must have compatible data types.
  • UNION removes duplicates; UNION ALL keeps them.
  • Column names in the result come from the first SELECT.

Side-by-Side Comparison

Feature JOIN UNION
Direction Horizontal (columns) Vertical (rows)
Combines Related columns Similar result sets
Requires A join condition (ON) Same column count & types
Duplicates N/A UNION removes, UNION ALL keeps
Result shape Wider table Taller table

Quick Example

-- JOIN: add department columns to each employee (horizontal)
SELECT e.name, d.dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id;

-- UNION: stack two lists of names into one column (vertical)
SELECT name FROM current_employees
UNION
SELECT name FROM former_employees;

-- UNION ALL: keep duplicates (faster, no dedupe)
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
Interviewer tip: The one-liner they want — "JOIN combines tables horizontally by adding related columns based on a condition, while UNION combines result sets vertically by stacking rows with matching columns."