SQL Tutorial 0/85 lessons ~6 min read Lesson 40

    SELF JOIN

    A self join joins a table to itself.

    Course progress0%
    Focus
    13 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    A self join joins a table to itself. Used for hierarchies (employee → manager), pairs of related rows (find duplicates) or comparing rows in the same table.

    Learning objective: Apply SELF JOIN correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.

    Treat every example as production-shaped SQL: explicit column lists, deterministic predicates, and indexes that match the access path. Prefer PostgreSQL dialect notes when dialects diverge; call out MySQL differences when they matter.

    Purpose of this lesson

    Apply SELF JOIN correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.

    Understanding the topic

    Core concepts to understand:

    • FROM employees e JOIN employees m ON e.manager_id = m.id.
    • Use distinct aliases for the two copies.
    • Common in org charts, threaded comments.
    • Find duplicates: FROM t a JOIN t b ON a.email=b.email AND a.id<b.id.
    • Recursive CTE often a cleaner alternative for hierarchies.

    Step-by-step explanation

    1. State the business question SELF JOIN answers and the tables involved.
    2. Read the workflow diagram and map each stage to parser, optimizer, or storage.
    3. Write the smallest correct statement (or design change) for a TechLearningPRO Orders/learners dataset.
    4. Predict the failure mode: wrong cardinality, missing index, or unsafe write — then verify.

    Syntax reference

    Visual workflow / architecture:

    bash
    employees employees
    e (worker) → m (manager)
    id manager_id id name
    1 NULL NULL
    2 1 1 CEO
    3 1 1 CEO
    4 2 2 CTO
    Syntax Pattern
    SELECT <cols>
    FROM   <t> AS a
    JOIN   <t> AS b
           ON  <a.col> = <b.related_col>;
    • SELF JOINJoins a table to itself — use two distinct aliases.
    • aliasesTreat each copy as a separate logical table.
    Live Example
    sql
    SELECT e.name AS worker, m.name AS manager
    FROM employees e
    JOIN employees m ON e.manager_id = m.id;
    employees
    idnamemanager_id
    1Ada (CEO)NULL
    2Leo1
    3Mia1
    4Rio2
    worker → manager
    workermanager
    LeoAda (CEO)
    MiaAda (CEO)
    RioLeo
    table Tjoined to itself

    Perfect for org charts, threaded comments, and finding duplicate rows.

    Informative example

    Worked SQL example:

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

    Real-world use

    Org-chart pages, 'find duplicate emails' admin queries, and threaded forum replies all use self-joins.

    Security implications

    SQL is a trust boundary. Application code must never concatenate untrusted input into statements.

    • Use bind parameters / prepared statements — never string-built SQL from request bodies.
    • Least-privilege DB roles: app users should not own DDL in production.
    • Avoid returning raw DB errors to clients; log server-side with a correlation id.

    Best practices

    • Use clear aliases (e, m).
    • Consider recursive CTEs for deep hierarchies.
    • Index the join column on both sides (it's the same column!).

    Common mistakes

    • Selecting * in application queries and shipping wide rows over the network.
    • Filtering on expressions that defeat indexes (WHERE YEAR(created_at) = 2026).
    • Running unbounded deletes/updates without a dry-run SELECT first.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionQ1. Why use a self join?+

    Answer

    Self join = table joined to itself.
    2IntermediateQuestionQ2. Find duplicate emails query.+

    Answer

    Great for hierarchies and pair-wise comparisons.
    3IntermediateQuestionQ3. Self join vs recursive CTE.+

    Answer

    Recursive CTE often cleaner.
    4AdvancedQuestionQ4. Aliasing rules.+

    Answer

    Recursive CTE often cleaner.
    5AdvancedQuestionQ5. Org-chart query example.+

    Answer

    Recursive CTE often cleaner.

    Hands-on exercise

    Hands-on + interview drill:

    • Implement the smallest correct example for SELF JOIN on an Orders-like schema.
    • Q1. Why use a self join?
    • Q2. Find duplicate emails query.
    • Q3. Self join vs recursive CTE.
    • Q4. Aliasing rules.
    • Q5. Org-chart query example.

    Summary

    SELF JOIN is a production SQL skill: state the question, write the precise statement, and prove it with an execution plan or constraint — not with lucky result sets.

    Ready to mark this lesson complete?Track your journey across the entire course.