Db2 Self-Join

Summary: in this tutorial, you will learn how to use Db2 self-join to join a table to itself to query hierarchical query or comparing rows within the same table.

Introduction to Db2 self-join

A self-join is a query in which a table is joined to itself using either INNER JOIN or LEFT JOIN clause. When you reference a table twice in a query, you have to use the table aliases.

The following illustrates the syntax of a self-join in Db2:

SELECT
    select_list
FROM
    table_name t1
    {LEFT | INNER} JOIN table_name t2
        ON join_condition;
Code language: SQL (Structured Query Language) (sql)

The self-join is useful to query hierarchical data or compare rows within the same table.

Db2 Self-Join examples

See the following genres table from the sample database:

In this table, the parent_id column references to the genre_id column to establish a parent-child relationship.

It means that for a genre you can use the value in the parent_id column to find its corresponding parent genre. The top genre has NULL in the parent_id column.

This query joins the genres table to itself by comparing values in the genre_id and parent_id columns. It returns all genres and their corresponding parent genres in the hierarchy of the genres:

SELECT 
    p.genre parent_genre, 
    c.genre sub_genre
FROM 
    genres c
    INNER JOIN genres p 
        ON p.genre_id = c.parent_id
ORDER BY 
    parent_genre, 
    sub_genre;
Code language: SQL (Structured Query Language) (sql)

Here is the partial output:

db2 self-join with inner join clause

In this example, the c and p are the table aliases for child and parent respectively.

To include the top genre in the result set, you need to use the LEFT JOIN instead of the INNER JOIN as shown in the following query:

SELECT 
    p.genre parent_genre, 
    c.genre sub_genre
FROM 
    genres c
    LEFT JOIN genres p 
        ON p.genre_id = c.parent_id
ORDER BY 
    parent_genre NULLS FIRST, 
    sub_genre;
Code language: SQL (Structured Query Language) (sql)

The following picture shows the partial output:

db2 self-join with left join clause

In this tutorial, you have learned how to use Db2 self-join to join a table to itself using either INNER JOIN or LEFT JOIN.

Was this tutorial helpful ?