Question: I need to compare two sets of rows within the same table, and I want to write a self-join in Oracle SQL. What are the ways to join an Oracle table with itself using an alias?
Oracle has several methods for joining a table to itself, and the SQL for self joins can be done several ways.
A self join is used to join a table to itself, and it is
commonly used when you have a table with dates and you want to compare one
date to another within the same table.
Visually, it sometimes helps to look at the table as two
identical tables (A and B). I am joining A to B, it just happens to be the
same table. Because the table is used twice in the query, you must alias the
table, and of course, you cannot use a natural join. In the example below, I
want a list of employees and their managers. In the EMP table, each employee
is identified by an emp_key. The employee's
manager is in the manager column and it contains the manager's
3 a.emp_last_name MANAGER
5 emp a
right outer join emp b on (a.emp_key = b.manager);
10 rows selected
As you can see, King is the manager for each of the
employees, and King does not have a manager assigned. I used an outer join
so that King would also be listed as an employee, even though he has no
manager. Otherwise, King would not have been listed. I join the
emp table to itself, joining where the
emp_key matched the manager.
It's very common to do a self join when comparing two rows in the same table and when comparing two ranges of rows within the same table. (For large complex comparisons of ranges of rows, some advocate self-joins using global temporary tables).
Here are the two most common ways to join a table with itself.
Traditional self-join: (note the old and new aliases for the table names)
to_char(snap_time,'yyyy-mm-dd HH24') mydate,
new.snap_id = sn.snap_id
old.snap_id = new.snap_id-1
old.namespace = new.namespace
Self join with analytic function:
sy.snap_id,sy.statistic# statistic#,sy.name statname,
sy.value - (LAG(sy.value)
OVER (PARTITION BY sy.name
ORDER BY sy.snap_id)) statdelta
FROM stats$sysstat sy
WHERE sy.snap_id IN (12208,12599,13480,13843)
AND sy.name IN
('consistent gets','consistent changes',
'db block gets', 'db block changes')
ORDER BY sy.name, sy.snap_id;