Self-Joins: Joining a Table to Itself, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 8.5 Free with a free account

Self-Joins: Joining a Table to Itself

Database Programming · Chapter 8: Joining Tables and Combining DataSection 8.5 · lesson 46 of 768 min · free with a free account

← Cross Joins: Generating Every CombinationNext lesson: Using Aliases to Simplify SQL Queries →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Join a table to itself for hierarchies, comparisons and duplicates.

  • Write a self-join with distinct aliases to list each employee beside their manager
  • Use a LEFT self-join to keep the root of a hierarchy
  • Find unordered pairs and duplicate candidates with an ascending-key condition
  • Explain when a fixed number of self-joins is enough and when recursion is needed

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (896 words). Read along, or search it.

Opening Problem

Staff and Managers in One Table

Maya Rao owns Lantern Books, our fictional bookstore. She asks for each staff member beside their manager, but both names live in one staff table. Amina Diallo manages operations in this teaching example, and Leo Park reports to Amina. Sofia Alvarez reports directly to Maya. We need the same stored table to play different roles. A self-join can follow those links, compare people, and find records worth reviewing.

Sample Data

A Self-Referencing Manager Column

Restore the shared bookstore, then add a disposable staff table using our established cast. Salaries and reporting links are invented teaching values. Each staff row has an identifier and a manager identifier. The latter references the primary key of the same table, a self-referencing foreign key. Maya has no manager in this example. Her null parent link identifies the root of this particular reporting hierarchy. Run the setup. A self-referencing foreign key checks referenced identities, but it does not by itself prevent cycles or guarantee a single rooted organization. A self-join does not physically photocopy the data. It gives separate names to separate uses of the same table within a query.

Role Aliases

Matching Employees to Their Managers

Alias e plays the employee, and alias m plays the manager. Distinct aliases let the database distinguish the two roles and their identically named columns. Match the employee’s manager identifier to the manager role’s staff identifier. Matching their staff identifiers instead would pair each person with themself. The output aliases employee and manager label two uses of name. Table aliases identify sources, while column aliases identify result labels. Run the left self-join. It follows each employee’s one-step parent link, while preserving employees who have no matching manager. Maya remains with a null manager; Amina and Sofia report to Maya, and Leo reports to Amina. An inner version would omit the root. A hierarchy organizes parent-child levels, such as staff reporting, categories, or comment threads. Its root has no parent, so preservation is an intentional decision.

Multiple Levels

Adding a Manager's Manager

Add a third role, g, for the manager’s manager. The first link uses e to m, and the second uses m to g. Each extra self-join follows one additional parent step. These inner joins require both steps to exist, so shallower staff rows will not survive. This is a fixed-depth question. An unknown-depth hierarchy needs a recursive query, with termination and cycle handling appropriate to its data. Run the three-role report. MySQL expresses recursion with with recursive; SQL Server uses recursive with without that additional keyword. Only Leo has both required ancestors: Amina and Maya. Adding aliases can answer a known number of levels, but it cannot automatically search every depth.

Value Comparison

Who Earns More Than Their Manager

A linked pair can also support a comparison. After connecting each person to their own manager, compare the two salary columns in where. This asks who earns more than their manager. Comparing arbitrary staff salaries without the manager link would answer a different question. A useful key index can help the lookup, but output size and the chosen plan still determine cost. A self-join is not automatically fast. Run the salary comparison. These illustrative amounts explain the predicate, rather than describing actual compensation or a recommended pay structure. Leo earns ninety thousand, compared with Amina’s eighty-five thousand. The result comes from both a relationship test and a value comparison.

Colleague Pairs

Removing Self-Pairs and Reversed Repeats

For colleague pairs, match departments. Operations has Amina and Leo, so an unrestricted match includes each person with both people, including themself. Requiring different identifiers removes self-pairs. It still includes Amina with Leo and Leo with Amina, called reversed repeats. Requiring the first identifier to be smaller keeps one orientation. For two different keys, exactly one direction satisfies that inequality. Run the three counts. All pairs gives four, different gives two, and ascending gives one unordered pair for this two-person department. To find one person’s colleagues, anchor that person and require a different colleague key. To list every unordered colleague pair, use the ascending-key condition.

Duplicate Review

Contacts Sharing an Email Address

Apply the pair pattern to a disposable contacts list. Two differently written names share Asha’s address, and another pair shares Ben’s address. Join on equal email values, then require ascending identifiers. This names both candidate records, rather than silently choosing which one to delete. Shared email is evidence for review, not proof of identical people. Missing email values do not match through ordinary equality. Run the candidate report. Equality’s case behavior depends on collation; differently capitalized addresses may compare differently across database settings. Two candidate pairs appear. The method finds exact matches under the chosen comparison rules, and does not automatically resolve spelling changes or household accounts.

Quick Check

Three Records With One Address

A new import contains three records with the same address, under identifiers four, seven, and nine. The program uses the ascending-key pair condition. How many candidate pairs will it report? Pause, and decide.

Answer

Three Unordered Candidate Pairs

Three candidate pairs. They are four with seven, four with nine, and seven with nine. The program confirms three. Every unordered pair appears once; the method does not reduce a three-record cluster to one row. Six would retain both directions of every non-self pair. Nine would also retain self-pairs, which the smaller-than condition prevents.

Key Takeaways

Distinct Aliases for Each Role

Maya can recover employee and manager names from one staff table, using distinct role aliases and the correct parent-to-key comparison. Use left join when the root must remain. Add a fixed role per known level, and use recursion when depth is not fixed. For unordered pairs, match the shared value and order the unique keys. Review duplicate candidates before changing any stored records.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Self-Joins: Joining a Table to Itself

What is a self-join in SQL?
A self-join joins a table to itself, using two aliases so the same table can play two roles. For a staff table whose manager_id references staff_id, SELECT e.name, m.name FROM staff AS e LEFT JOIN staff AS m ON e.manager_id = m.staff_id lists each employee beside their manager. Matching e.staff_id = m.staff_id instead would match each row with itself. No data is copied; the aliases only name roles.
Why use a LEFT JOIN in an employee-manager self-join?
A LEFT JOIN keeps employees who have no manager, such as the owner at the top of the hierarchy, whose manager_id is NULL. With an inner self-join, that root row finds no match and disappears from the report. The preserved row simply shows NULL in the manager column. Keeping or dropping the root is a reporting decision, so choose the join type on purpose.
How do you find pairs of rows without duplicates in a self-join?
Join the table to itself on the shared value and require the first key to be smaller than the second, as in ON a.email = b.email AND a.id < b.id. The less-than test removes self-pairs and keeps one orientation of each reversed pair. Records 4, 7 and 9 with one email give three pairs: 4-7, 4-9 and 7-9. Using <> instead would return six, both directions of each pair.
How do you find employees who earn more than their manager in SQL?
Self-join the staff table to link each employee to their own manager, then compare the two salary columns in WHERE: SELECT e.name FROM staff AS e JOIN staff AS m ON e.manager_id = m.staff_id WHERE e.salary > m.salary. The join supplies the relationship and WHERE supplies the value test. Comparing salaries without the manager link would answer a different question about arbitrary pairs of staff.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →