SQL Self Join

Join a table with itself.

✍️ 3 exercises + code challenge in this lesson

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.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services