Sub topic 11
Self Joins and Non-Equi Joins
This chapter covers two join patterns that go beyond the usual "match a foreign key to a primary key" case. A self join combines a table with itself. A non-equi join uses a comparison other than = in the join condition. Both use the same ANSI JOIN ... ON syntax you already know.
Prerequisites
This chapter assumes you can write inner and outer joins with ON, use table aliases, and explain what NULL means in a comparison. It uses the Oracle HR sample schema: employees, departments and jobs. It also uses a small salary_grades table that you create in the non-equi section.
Self joins
A self join is a join where both sides are the same table. Oracle does not need special syntax for it. You list the table twice and give each occurrence its own alias, so the optimizer and you can tell the two roles apart.
The classic case is a hierarchy stored in one table. In employees, the column manager_id holds the employee_id of another row in the same table. To show each employee next to their manager's name, treat one copy of the table as the employees and the other copy as the managers.
SELECT e.last_name AS employee,
m.last_name AS manager
FROM employees e
LEFT OUTER JOIN employees m
ON e.manager_id = m.employee_id
ORDER BY e.last_name;The alias e plays the employee role and m plays the manager role. The condition e.manager_id = m.employee_id links the foreign key in one role to the primary key in the other.
Why LEFT OUTER JOIN here
The top of the hierarchy, usually the company president, has a NULL manager_id. A NULL never equals anything, so an inner join drops that row. Using LEFT OUTER JOIN keeps every employee, and the manager column shows NULL for the person with no manager.
SELECT e.last_name AS employee,
m.last_name AS manager
FROM employees e
JOIN employees m
ON e.manager_id = m.employee_id
ORDER BY e.last_name;This inner join version returns one row fewer than the outer join version in the standard HR data, because the employee with no manager is missing.
The same query in (+) syntax
You may meet the older form in legacy code. The (+) goes on the side that may lack a match, which is the manager alias.
SELECT e.last_name AS employee,
m.last_name AS manager
FROM employees e, employees m
WHERE e.manager_id = m.employee_id(+)
ORDER BY e.last_name;Going up more than one level
A self join only reaches one level of the hierarchy. To show an employee, their manager and their manager's manager, join the table a third time under a third alias.
SELECT e.last_name AS employee,
m.last_name AS manager,
gm.last_name AS grand_manager
FROM employees e
LEFT OUTER JOIN employees m ON e.manager_id = m.employee_id
LEFT OUTER JOIN employees gm ON m.manager_id = gm.employee_id
ORDER BY e.last_name;Each added level adds another join. For hierarchies of unknown depth, Oracle's CONNECT BY clause or a recursive WITH query is a better tool than a chain of self joins.
Pairs of rows from the same table
A self join can also compare rows that are peers. A frequent task is to find pairs of employees who share a job. To avoid listing each pair twice, and to avoid pairing a row with itself, use an inequality on the key.
SELECT a.last_name AS employee_1,
b.last_name AS employee_2,
a.job_id
FROM employees a
JOIN employees b
ON a.job_id = b.job_id
AND a.employee_id < b.employee_id
ORDER BY a.job_id, a.last_name;The condition a.employee_id < b.employee_id is a non-equi condition. It keeps each unordered pair once. With <> instead of <, you would get every pair twice, once in each order.
Non-equi joins
An equi join compares columns with =. A non-equi join uses another comparison: <, <=, >, >=, <>, or BETWEEN. The most common use is matching a value to a range.
Matching a value to a range with BETWEEN
Suppose you keep salary bands in a lookup table. The table has no foreign key to employees. A salary belongs to a band because it falls between two limits.
CREATE TABLE salary_grades (
grade_level VARCHAR2(2) PRIMARY KEY,
lowest_sal NUMBER(8,2) NOT NULL,
highest_sal NUMBER(8,2) NOT NULL
);
INSERT INTO salary_grades VALUES ('A', 1000, 2999.99);
INSERT INTO salary_grades VALUES ('B', 3000, 5999.99);
INSERT INTO salary_grades VALUES ('C', 6000, 9999.99);
INSERT INTO salary_grades VALUES ('D', 10000, 14999.99);
INSERT INTO salary_grades VALUES ('E', 15000, 40000);
COMMIT;Now join each employee to the band that contains their salary.
SELECT e.last_name, e.salary, g.grade_level
FROM employees e
JOIN salary_grades g
ON e.salary BETWEEN g.lowest_sal AND g.highest_sal
ORDER BY e.salary DESC;BETWEEN is inclusive at both ends. If two bands overlap, an employee whose salary falls in the overlap appears once per matching band. If a salary falls in a gap between bands, the employee has no match and an inner join drops that row. To keep such employees, use a LEFT OUTER JOIN.
SELECT e.last_name, e.salary, g.grade_level
FROM employees e
LEFT OUTER JOIN salary_grades g
ON e.salary BETWEEN g.lowest_sal AND g.highest_sal
ORDER BY e.salary DESC;Employees that fall in a gap show a NULL grade_level. That makes the gap visible instead of hiding it.
Non-equi joins in (+) syntax
The (+) marker works with range conditions too. Put it on each column of the outer table. Oracle also restricts how (+) can combine with BETWEEN, IN and OR, and that is where the older syntax gets awkward.
SELECT e.last_name, e.salary, g.grade_level
FROM employees e, salary_grades g
WHERE e.salary >= g.lowest_sal(+)
AND e.salary <= g.highest_sal(+);Writing the range as two comparisons with (+) on both g columns is the dependable form. The ANSI version with ON ... BETWEEN is easier to read and carries none of these restrictions.
Comparing a row to an earlier or later row
Non-equi joins also compare rows by order. This query finds, for each employee, the number of colleagues hired earlier.
SELECT e.last_name,
e.hire_date,
COUNT(p.employee_id) AS hired_before
FROM employees e
LEFT OUTER JOIN employees p
ON p.hire_date < e.hire_date
GROUP BY e.last_name, e.hire_date
ORDER BY e.hire_date;This is a self join and a non-equi join at once. It works, but it compares every pair of rows, so the cost grows with the square of the row count. Analytic functions such as ROW_NUMBER() or RANK() do this job with a single pass over the table, so prefer them on large tables.
Performance and correctness notes
Equi joins can use hash joins and sort-merge joins. Oracle can run a hash join only on equality conditions. A pure non-equi join falls back to nested loops or, in some cases, a merge join, which can be much slower on large tables. Two rules help:
- Include an equality condition in the join whenever you can. In the job-pairs example,
a.job_id = b.job_idlets Oracle group the rows first and apply the<test only within each group. - Index the columns used in range conditions. An index on
lowest_salor onhire_datehelps nested loops probe efficiently.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| ORA-00918: column ambiguously defined | A self join column was not qualified with an alias | Prefix every column with `e.` or `m.` |
| Top-level employee missing | Inner join drops the NULL `manager_id` row | Use `LEFT OUTER JOIN` |
| Each pair appears twice | Used `<>` between keys | Use `<` on the key |
| Employee appears twice with a band lookup | Bands overlap | Fix the lookup data or add a uniqueness check |
| Employee missing from band lookup | Salary falls in a gap between bands | Use a `LEFT OUTER JOIN` and close the gap |
| Row pairs with itself | No condition excludes equal keys | Add `a.employee_id < b.employee_id` |
Summary
- A self join lists one table twice with two different aliases. Use an outer join when some rows, such as the top of a hierarchy, have no partner.
- A non-equi join uses
<,>,<=,>=,<>orBETWEEN. It is the natural way to match a value to a range. - Overlapping ranges multiply rows, and gaps between ranges remove rows from an inner join.
- Add an equality condition to a non-equi join when possible so Oracle can reduce the number of rows it compares.
Exercise
Using the HR schema, write an ANSI query that lists each employee's last name together with the last name of their manager, and keeps employees who have no manager. Then say which join type you chose and why.
Show answer
SELECT e.lastname AS employee, m.lastname AS manager FROM employees e LEFT OUTER JOIN employees m ON e.managerid = m.employeeid; A LEFT OUTER JOIN is needed because the top employee has a NULL managerid. An inner join would drop that row, since NULL never equals any employeeid. The alias e is the employee role and the alias m is the manager role.
Exercise
The query below is meant to list each pair of employees in the same department once. It returns every pair twice and also pairs each employee with themselves. Fix the ON clause. SELECT a.lastname, b.lastname FROM employees a JOIN employees b ON a.departmentid = b.departmentid;
Show answer
Add a non-equi condition on the key: ON a.departmentid = b.departmentid AND a.employeeid < b.employeeid. The condition removes self-pairs because an employee_id is never less than itself. It also keeps only one of the two orderings of each pair.
Exercise
A salarygrades table has a band from 3000 to 5999.99 and the next band from 6000 to 9999.99. An employee earns 5999.995. What does an inner join with ON e.salary BETWEEN g.lowestsal AND g.highest_sal return for this employee, and how would you keep the employee in the result?
Show answer
The salary is greater than 5999.99 and less than 6000, so it falls in the gap and matches no band. The inner join drops the employee. Switching to a LEFT OUTER JOIN keeps the employee with a NULL gradelevel. A longer-term fix is to define the bands without gaps, for example with ON e.salary >= g.lowestsal AND e.salary < g.nextlowestsal.