In this lesson, you will learn how to use a self-join to compare records within the same table by treating one table as two separate entities.
The Core Concept
A self-join is simply joining a table to itself. This is incredibly powerful when your table contains related entities that need to be compared side-by-side. Instead of looking at a single row in isolation, you create a "pairwise" view where each row is matched against another based on a specific logic, such as comparing a product with its direct competitor or checking sequential events for the same user.
Illustration: Pairwise Product Analysis
Imagine a products table with columns product_name and category. If you want to list all possible pairs of products within the same category to identify potential cross-sell opportunities, you join the table to itself.
To avoid comparing a product to itself (e.g., "Apple" with "Apple") and to avoid duplicate pairs (e.g., "Apple vs. Banana" and "Banana vs. Apple"), we use an inequality operator in our JOIN condition:
SELECT
p1.product_name AS item_a,
p2.product_name AS item_b,
p1.category
FROM products p1
JOIN products p2
ON p1.category = p2.category
AND p1.product_name < p2.product_name;
Why use <?
By using p1.product_name < p2.product_name, we enforce two rules:
- Uniqueness: We never match a product with itself because a value is never strictly less than itself.
- Efficiency: We ensure that each unique pair is only returned once. If we used
!=, we would get every pair twice (both A-B and B-A), which clutters our analysis.
This logic allows you to extract relationships that are otherwise hidden. Whether you are identifying overlapping memberships or comparing performance metrics between different departments stored in the same list, the self-join provides the bridge needed to view your data as a collection of interacting pairs.
Key Takeaway: A self-join allows you to compare rows against one another by assigning aliases to the same table, using inequality conditions to filter for meaningful, non-redundant pairs.