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 →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| product_a | product_b | brand | price_a | price_b |
|---|---|---|---|---|
| P001 | P002 | NovaTech | 299.99 | 149.99 |
| P003 | P004 | UrbanWear | 59.99 | 89.99 |
Step by step
- 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 - 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 - 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
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_id2. 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_id3. 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_id4. 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_id5. 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_idLearn 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 →