Practice Free
MediumJoins

Organizational Chart Hierarchy with SELF JOIN

Frequently Asked By:AppleGoogleAmazon
Interactive In-Browser Workspace

Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.

Solve in Workbench

Problem Statement

Join the `employees` table to itself (Self-Join) matching each employee's `manager_id` to the manager's `emp_id`. Return: 1. `e.emp_id` 2. `e.full_name` AS `employee_name` 3. `e.job_title` 4. `COALESCE(m.full_name, 'Executive Board')` AS `manager_name` Use a `LEFT JOIN` so employees without a manager (CEOs/founders) are retained. Order the results by `e.emp_id` ascending.

Why Technical Interviewers Ask This

During company-wide re-org planning, HR needs a consolidated management report displaying each employee alongside the full name of their direct manager. For top executives with no manager, display 'Executive Board'.

Common Pitfalls & Interview Traps

Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass joins constructs.

Canonical Modern SQL Solution

PostgreSQL 16 / ANSI SQL
SELECT 
        e.emp_id,
        e.full_name AS employee_name,
        e.job_title,
        COALESCE(m.full_name, 'Executive Board') AS manager_name
      FROM employees e
      LEFT JOIN employees m ON e.manager_id = m.emp_id
      ORDER BY e.emp_id ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Joins. It meets the target criteria: Org chart hierarchy showing employee name, title, and manager name.

Edge Cases to Verbally Clarify with Your Interviewer

The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.

Frequently Asked Follow-Up Questions

What makes this question a favorite among Apple and Google interviewers?

Interviewers use this problem to test whether candidates write defensive, scalable Joins queries that run efficiently on multi-million row production databases without excessive memory usage.

How does the query optimizer execute this query?

Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.

More FAANG SQL Interview Questions

View all questions