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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Using Aliases to Simplify SQL Queries →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
Why use a LEFT JOIN in an employee-manager self-join?
How do you find pairs of rows without duplicates in a self-join?
How do you find employees who earn more than their manager in SQL?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →