A self join joins a table to itself, using two different aliases. It is useful to compare rows within the same table.
The example finds pairs of customers who live in the same city. The condition a.CustomerID < b.CustomerID avoids pairing a customer with themselves and listing each pair twice.
💡 Key Takeaways: SQL Self Join
Mastering SQL Self Join helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
SQL Self Join Code Example
SQL
SELECT a.CustomerName AS Customer1,
b.CustomerName AS Customer2,
a.City
FROM Customers a
JOIN Customers b
ON a.City = b.City AND a.CustomerID < b.CustomerID;
Free sign-in required · Google login available
SQL Self Join Practice Exercises
Check what you learned in “SQL Self Join”.
/ 3 solved
Fill in the blank
Join the table to itself with two aliases.
FROM Customers a JOIN Customers ON a.City = b.City
✓ Correct!Not quite. Try again.
Multiple choice
Why use a self join?
✓ Correct!Not quite. Try again.
Code challenge
List pairs of customer names (Customer1, Customer2) in the same City, each pair once (a.CustomerID < b.CustomerID), sorted by Customer1.
Write the code in the live editor. Your answer is checked automatically.