Sub topic 6
Comparing rows: pairs without duplicates or mirror images
A self join can match each row with a parent row. It can also match each row with its peers. This chapter covers the second use: finding pairs of rows in one table that share a value, and returning each pair exactly once.
This chapter assumes you can write an INNER JOIN with an ON condition, you know what a primary key is, and you know that NULL = NULL is not true in SQL. It builds on the employees table and the aliases e and m from the earlier chapters.
The goal: colleagues who share a manager
Suppose you want every pair of employees who report to the same manager. The table looks like this:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INT REFERENCES employees(id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dana', 2);The natural first attempt joins the table to itself on manager_id:
SELECT a.name AS first_employee, b.name AS second_employee
FROM employees a
INNER JOIN employees b
ON a.manager_id = b.manager_id
ORDER BY a.id, b.id;You want one row, Ben and Chen. The query returns five:
| first_employee | second_employee |
|---|---|
| Ben | Ben |
| Ben | Chen |
| Chen | Ben |
| Chen | Chen |
| Dana | Dana |
Two kinds of unwanted rows appear.
- Self-pairs match a row with itself: Ben with Ben, Chen with Chen, Dana with Dana. Every row satisfies
a.manager_id = b.manager_idagainst itself. - Mirrored pairs list the same two people in both orders: Ben with Chen, and Chen with Ben.
Ava does not appear at all. Her manager_id is NULL, and NULL = NULL evaluates to unknown, so the ON condition never matches her.
Why these rows appear
A self join with only an equality condition builds a block of rows for each shared value. If a manager has n direct reports, that group contributes n × n rows. The block has three parts:
- n self-pairs on the diagonal.
- n × (n − 1) / 2 pairs in one order.
- n × (n − 1) / 2 pairs in the other order.
Only the middle count of pairs is what you want. The diagram shows how to cut the block down.
Removing self-pairs with an inequality
Adding a.id <> b.id removes every self-pair:
SELECT a.name AS first_employee, b.name AS second_employee
FROM employees a
INNER JOIN employees b
ON a.manager_id = b.manager_id
AND a.id <> b.id
ORDER BY a.id, b.id;The result is Ben with Chen and Chen with Ben. The mirrored pair is still there, because <> is symmetric. If (a, b) passes, then (b, a) passes too.
Removing both with a strict ordering
Replace <> with <:
SELECT a.name AS first_employee, b.name AS second_employee
FROM employees a
INNER JOIN employees b
ON a.manager_id = b.manager_id
AND a.id < b.id;This returns only Ben and Chen. The condition works for two reasons:
- A row is never strictly less than itself, so self-pairs fail.
- For any two different rows, exactly one of
a.id < b.idandb.id < a.idis true, so exactly one order survives.
< is the idiom for unordered pairs. Use > instead if you want the larger id on the left. Either choice gives the same set of pairs.
Which column to compare
Compare a column that is unique for every row, normally the primary key. A column with possible ties breaks the guarantee.
Suppose you wrote a.name < b.name, and two employees were both called Sam. Neither Sam < Sam comparison is true, so the pair would vanish. If you want to order by something else, such as name, add the key as a tiebreaker:
ON a.manager_id = b.manager_id
AND (a.name < b.name OR (a.name = b.name AND a.id < b.id))In most cases a.id < b.id is simpler and enough.
Counting pairs in a larger team
The sample data has only one pair. Add two more employees to see the growth:
INSERT INTO employees (id, name, manager_id) VALUES
(5, 'Eli', 1),
(6, 'Fay', 2);Ava now has three direct reports (Ben, Chen, Eli), and Ben has two (Dana, Fay). Here is how each version of the join counts rows:
| Join condition | Rows |
|---|---|
| `a.manager_id = b.manager_id` | 13 (3 × 3 + 2 × 2) |
| plus `a.id <> b.id` | 8 |
| plus `a.id < b.id` | 4 |
The four pairs are Ben and Chen, Ben and Eli, Chen and Eli, and Dana and Fay.
The pair count for a group of n is n × (n − 1) / 2, which grows with the square of the group size. A manager with 100 reports produces 4,950 pairs. A manager with 10,000 reports produces almost 50 million. Self joins on a low-cardinality column (one with few distinct values) are the usual cause of surprise row counts.
Finding duplicates
The same pattern finds duplicate values in any table. Here is a contact list with a repeated email address:
CREATE TABLE contacts (
id INT PRIMARY KEY,
email VARCHAR(50) NOT NULL
);
INSERT INTO contacts (id, email) VALUES
(1, '[email protected]'),
(2, '[email protected]'),
(3, '[email protected]'),
(4, '[email protected]');
SELECT a.id AS first_id, b.id AS second_id, a.email
FROM contacts a
INNER JOIN contacts b
ON a.email = b.email
AND a.id < b.id
ORDER BY a.id, b.id;The result has three rows: ids 1 and 3, ids 1 and 4, and ids 3 and 4. Three copies of one email give three pairs, which is the n × (n − 1) / 2 formula with n = 3.
Because every pair is listed, this form shows exactly which rows clash. If you only need a list of duplicated values, GROUP BY email HAVING COUNT(*) > 1 is cheaper. Use the self join when you need the ids of both rows or want to compare other columns of the two rows.
Comparing other columns of the pair
The ON condition can hold any test on the two rows, so you can combine the ordering rule with other conditions. For example, you can find pairs of colleagues where one was hired at least a year before the other, if the table has a hired_on date column. You would write the same-manager test, then a.id < b.id, then a date test.
When the question is directional, you do not need the < trick. "Employees who earn more than their manager" is a self join on e.manager_id = m.id with e.salary > m.salary. The roles are different (employee and manager), so each result row is already a distinct, ordered fact.
Where to put the condition
For an INNER JOIN, a condition in ON and the same condition in WHERE give the same result. This also works:
SELECT a.name, b.name
FROM employees a
INNER JOIN employees b ON a.manager_id = b.manager_id
WHERE a.id < b.id;Keeping the pair rule in ON is clearer, because it shows that the rule belongs to the pairing. The difference matters with a LEFT JOIN. A WHERE condition on the right-hand table filters out the NULL-extended rows and turns the join into an INNER JOIN. Pair comparisons almost always use INNER JOIN, since a row with no partner is not a pair.
Three or more rows
To list triples with no repeats, chain the ordering:
SELECT a.name AS first_employee,
b.name AS second_employee,
c.name AS third_employee
FROM employees a
INNER JOIN employees b
ON a.manager_id = b.manager_id AND a.id < b.id
INNER JOIN employees c
ON b.manager_id = c.manager_id AND b.id < c.id
ORDER BY a.id, b.id, c.id;Because a.id < b.id and b.id < c.id, each set of three people appears once, in increasing id order. With the six employees above, Ava's team gives one triple: Ben, Chen and Eli.
Checking your result
Three quick checks catch most mistakes:
- Count the rows and compare with the formula. For a join on one shared value, add up n × (n − 1) / 2 over the groups.
- Look for rows where both columns show the same person. Any such row means the ordering condition is missing or wrong.
- Look for a pair that also appears reversed. If you find one, you used
<>where you needed<.
You can also run the filtered query and test the formula in SQL:
SELECT COUNT(*) AS pair_count
FROM employees a
INNER JOIN employees b
ON a.manager_id = b.manager_id
AND a.id < b.id;After the two inserts above, this returns 4.
Summary of the pattern
| Goal | Condition added to the equality join |
|---|---|
| Every row with every row sharing the value, including itself | none |
| Ordered pairs, each person against every other | `a.id <> b.id` |
| Unordered pairs, each listed once | `a.id < b.id` |
| Unordered triples | `a.id < b.id` and `b.id < c.id` |
Exercise
The table contacts has ids 1 to 4 and emails [email protected] (ids 1, 3, 4) and [email protected] (id 2). How many rows does the self join on email return with no extra condition, with a.id <> b.id, and with a.id < b.id?
Show answer
With no extra condition it returns 10 rows: 3 × 3 = 9 for the first email plus 1 × 1 = 1 for the second. With a.id <> b.id it returns 6 rows, because the 4 self-pairs are removed (3 for the first email and 1 for the second). With a.id < b.id it returns 3 rows, which is 3 × 2 / 2 for the first email and 0 for the second.
Exercise
Write a query on the employees table that returns each pair of employees with the same manager exactly once, and explain why a.name < b.name is a weaker choice than a.id < b.id.
Show answer
SELECT a.name AS firstemployee, b.name AS secondemployee FROM employees a INNER JOIN employees b ON a.managerid = b.managerid AND a.id < b.id; The id column is a primary key, so it is unique and gives a strict order. The name column can have ties. If two employees under one manager share a name, neither a.name < b.name comparison is true, so that pair would be dropped from the result.