skip to Main Content

I’m new to SQL and I don’t understand why you need a <> condition in a self join like below. I get that a join with an equal to condition won’t return any results but I can’t get my head around the need for <> in this case.

Please let me know if I need to provide any other info to answer this.

SELECT DISTINCT
    t1.number AS num1,
    t2.number AS num2
FROM transportation_numbers t1
JOIN transportation_numbers t2 ON t1.index <> t2.index
WHERE
    t1.number < t2.number AND
    t1.number * t2.number > 11

2

Answers


  1. This means that each row in a table is joined to itself and every other row in that table.

    SELECT
       A.LName AS Employee1
       ,B.LName AS Employee2
       ,A.City
    FROM Employee A, Employee B
    WHERE A.LName < B.LName
    AND A.City = B.City
    ORDER BY A.City;
    
    Login or Signup to reply.
  2. I’ve used it many times in things like self joins across one column that is not a unique identifier/key and then use the <> to prevent joining the same ID to itself.

    Something like

    SELECT a.id, 
        a.otherCol, 
        b.id, 
        b.otherCol
    FROM T AS a INNER JOIN 
        T AS b ON b.someCol = a.someCol AND a.id <> b.id
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search