Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Medical Center database
Non primary-foreign key JOINs
Non-equi JOINs
Non-equi self JOINs
19. NON-EQUI self JOINs
Summary

Instruction

Great! The non-equi JOIN comes in handy especially when you have to join a table with itself. For example you can select all the items from a table and pair them, either in unique or non-unique pairs.

Suppose you have the Items table, and you want to find all possible combinations of all item pairs for a special promotion. You would like to show all possible pairs, excluding only the case when a given item matches itself (that is, the pair consists of two copies of the same item):

SELECT
  Item1.Name,
  Item2.Name
FROM Items Item1
JOIN Items Item2
  ON Item1.Id != Item2.Id

Great! Everything works... However, with this query, we don't get unique pairs - because the result also includes pairs in reverse order. What about unique pairs? Well, in that case, we have to change the inequality operator to the less-than operator (<):

SELECT
  Item1.Name,
  Item2.Name
FROM Items Item1
JOIN Items Item2
  ON Item1.Id < Item2.Id

Why? Suppose we have only three items in the items table. The item with the smallest ID (Id = 1) can be listed as the first element of two pairs: 1 & 2 and 1 & 3. But because of the less-than operator, the item with Id = 2 can only be listed together with item 3. And the item with Id = 3 is never listed as the first member of a pair. With this little trick, we have unique pairs!

Exercise

Take a look at the Employee table. It contains the following columns:

  • Id – the ID of a given employee,
  • Name – the name of a given employee,
  • Position – the position of a given employee,
  • Department – the department of a given employee, and
  • Age – the age of a given employee.

Join the table with itself and connect all employees in pairs, showing their names. Display only unique pairs of employees.

Stuck? Here's a hint!

Type:

SELECT
  Emp1.Name,
  Emp2.Name
FROM Employee Emp1
JOIN Employee Emp2
  ON Emp1.Id  < Emp2.Id