Database Tutorial

Course Tutorial Site

Site Admin

Self Joins

with 3 comments

A self join can be an INNER, LEFT, RIGHT, or FULL JOIN. A table supports a self join when it contains a PRIMARY KEY and FOREIGN KEY that points to it’s own PRIMARY KEY. This means you can join a row in the table to the same row or another row in the table, and the join is wholly dependent on the matching of values in the PRIMARY and FOREIGN KEY column(s).

A self join acts like a nested loop where you match a key from the outer loop against a key from the inner loop. The trick is that the outer and inner loop hold different copies of the same data set. You effectively tie together two rows into one master set of information, much as you would rows from different tables in any other join operation.

Written by michaelmclaughlin

January 18th, 2010 at 10:21 pm

Posted in

3 Responses to 'Self Joins'

Subscribe to comments with RSS or TrackBack to 'Self Joins'.

  1. I believe I understand the concept and how to implement a self join, but is there an example of a ‘real-world’ situation that would call for a self join? I’m just drawing a blank as to when I would use this.

    Josiah

    5 Feb 10 at 12:50 pm

  2. Sure, in this example you’re discovering who gave access to somebody. It’s done by leveraging the “who-audit” columns of CREATED_BY and LAST_UPDATED_BY. These two columns can be tied to the same or different rows in the SYSTEM_USER table. Any attempt to find both the creator or last updator of a row in the table requires a self-join to link the two rows together.

    You can also check the hierarchical join mechanics for an organization to see another concrete example.

    michaelmclaughlin

    5 Feb 10 at 1:03 pm

  3. Thanks.

    Josiah

    5 Feb 10 at 1:42 pm

Leave a Reply