BBampaa

Lessons › SQL › Deep Dive: Advanced Joins & Subqueries

SQL lesson

Self join basics

A self join treats a single table as if it were two separate tables, letting you compare rows within that table against each other.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Comparing Products with a Self Join

SELECT p1.product_id AS product_a,
       p2.product_id AS product_b,
       p1.brand,
       p1.price AS price_a,
       p2.price AS price_b
FROM products p1
JOIN products p2
  ON p1.brand = p2.brand
WHERE p1.product_id < p2.product_id

Result:

product_aproduct_bbrandprice_aprice_b
P001P002NovaTech299.99149.99
P003P004UrbanWear59.9989.99

Step by step

  1. AS gives a column a friendlier name in the result.
    SELECT p1.product_id AS product_a, p2.product_id AS product_b, p1.brand, p1.price AS price_a, p2.price AS price_b
  2. FROM tells SQL which table to pull the data from.
    SELECT p1.product_id AS product_a, p2.product_id AS product_b, p1.brand, p1.price AS price_a, p2.price AS price_b
    FROM products p1
  3. JOIN combines rows from two tables that share a key.
    SELECT p1.product_id AS product_a, p2.product_id AS product_b, p1.brand, p1.price AS price_a, p2.price AS price_b
    FROM products p1
    JOIN products p2 ON p1.brand = p2.brand

Practice

Try each one in your head first, then open the answer.

1. Using orders aliased as t1 and t2, write a self join on the order_id column.
SELECT * FROM orders t1 INNER JOIN orders t2 ON t1.order_id = t2.order_id
2. Using orders aliased as t1 and t2, write a self join on the order_id column.
SELECT * FROM orders t1 INNER JOIN orders t2 ON t1.order_id = t2.order_id
3. Using orders aliased as t1 and t2, write a self join on the order_id column.
SELECT * FROM orders t1 INNER JOIN orders t2 ON t1.order_id = t2.order_id
4. Using products aliased as t1 and t2, write a self join on the product_id column.
SELECT * FROM products t1 INNER JOIN products t2 ON t1.product_id = t2.product_id
5. Using products aliased as t1 and t2, write a self join on the product_id column.
SELECT * FROM products t1 INNER JOIN products t2 ON t1.product_id = t2.product_id

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed