Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials MySQL Self Join & UNION
MySQL Intermediate FREE

Self Join & UNION

Lesson 2 of 16 Intermediate Interactive

Self Join joins a table with itself (e.g., employees/managers).

UNION

Combines results from two SELECTs. UNION ALL keeps duplicates.

Syntax

MYSQL
SELECT e.name, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

SELECT name, email FROM customers
UNION
SELECT name, email FROM vendors;
Self Joins and UNION
SQL
-- Self join: employees and managers
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

-- UNION removes duplicates
SELECT name FROM customers
UNION
SELECT name FROM suppliers
ORDER BY name;

-- UNION ALL keeps duplicates
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;

-- UNION with different tables
SELECT id, "order" AS src FROM orders
UNION
SELECT id, "refund" AS src FROM refunds;

Practice

1
Exercise

Find employees with no manager.

Answer
SELECT e.name FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
WHERE m.id IS NULL;

Quick Quiz

1

UNION vs UNION ALL?

UNION removes duplicates; UNION ALL keeps all rows.

Interview Questions

Hierarchical data (org charts), comparing rows (sequential data), finding relationships within the same table.