A join does not always have to involve two different tables.
You can join a table to itself, creating a self-join.
Joining a table to itself can be useful when you want to compare values
in a column to other values in the same column.
To create a
self-join, list a table twice in the FROM clause, and assign it a
different alias each time. Use the aliases to refer to the table in
the Projection and WHERE clauses as if it were two separate tables.
(Aliases in SELECT statements are discussed in Aliases and in the HCL OneDB™ Guide to SQL:
Syntax.)
Just
as in joins between tables, you can use arithmetic expressions in
self-joins. You can test for null values, and you can use an ORDER
BY clause to sort the values in a specified column in ascending or
descending order.
The following query finds pairs of orders where the ship_weight differs
by a factor of five or more and the ship_date is not null.
The query then orders the data by ship_date.
Table 1. Query result
order_num
ship_weight
ship_date
order_num
ship_weight
ship_date
1004
95.80
05/30/1998
1011
10.40
07/03/1998
1004
95.80
05/30/1998
1020
14.00
07/16/1998
1004
95.80
05/30/1998
1022
15.00
07/30/1998
1007
125.90
06/05/1998
1015
20.60
07/16/1998
1007
125.90
06/05/1998
1020
14.00
07/16/1998
If you want to store the results of a self-join into a
temporary table, append an INTO TEMP clause to the SELECT statement
and assign display labels to at least one set of columns to rename
them. Otherwise, the duplicate column names cause an error and the
temporary table is not created.
The following query, which is similar to Query, labels all columns selected
from the orders table and puts them in a temporary table called shipping.
If you query with SELECT * from table shipping,
you see the following rows.
You can join a table to itself more than once. The maximum
number of self-joins depends on the resources available to you.
The self-join in the following query creates a list of
those items in the stock table that are supplied by three manufacturers.
The self-join includes the last two conditions in the WHERE clause
to eliminate duplicate manufacturer codes in rows that are retrieved.
If you want to select rows from a payroll table to determine
which employees earn more than their manager, you might construct
the self-join as the following SELECT statement shows:
SELECT emp.employee_num, emp.gross_pay, emp.level,
emp.dept_num, mgr.employee_num, mgr.gross_pay,
mgr.dept_num, mgr.level
FROM payroll emp, payroll mgr
WHERE emp.gross_pay > mgr.gross_pay
AND emp.level < mgr.level
AND emp.dept_num = mgr.dept_num
ORDER BY 4;
The following query uses a correlated subquery to
retrieve and list the 10 highest-priced items ordered.
The query returns the 10 rows.
You can create a similar query to find and list the 10
employees in the company who have the most seniority.