Beginner LevelSQL & MySQL
What is a Self-Join and how is it used for organizational hierarchies?
❓ Interview Prompt: Explain `Self-Join` mechanics, joining a table to itself using table aliases, and querying employee-manager hierarchies.
A Self-Join is a regular join operation in which a table is joined with itself using table aliases:
Use Case:
Querying hierarchical or recursive relationships stored within a single table (e.g. employee-manager hierarchies or category-parent categories).
Code Implementation Example
sql
-- Self-Join mapping employees to their managers
SELECT
e.name AS employee_name,
COALESCE(m.name, 'Top Executive') AS manager_name
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;💡Querying employee-manager relationships with a Self-Join.
🎯 Interview Key Takeaway
Use Self-Joins with table aliases to resolve parent-child relationships stored in a single table.
#SQL#Self Join#Hierarchies#Aliases#Beginner
Back to all SQL & MySQL Questions→