Search code examples
sqlinner-joinself-join

self join ON clause in SQL


I'm having trouble understanding why the output is the way it is for this self join. The code for the table I'm dealing with is:

create table point_2d (x INT, y INT);
insert into point_2d values (-1, -1);
insert into point_2d values (0,0);
insert into point_2d values (-1, -2);

I want to execute a self join as follows:

SELECT *
FROM
point_2d p1
Inner JOIN
point_2d p2
ON p1.x != p2.y;

it's the ON clause that's confusing me with the output. How exactly is this table self-joining given the condition

p1.x != p2.y

in the code above?


Solution

  • in some databases the != operator is write like <>, the query will be the same

    SELECT *
    FROM
    point_2d p1
    Inner JOIN
    point_2d p2
    ON p1.x <> p2.y;
    

    If you don't like use the expllicit join, you can also use this way

    SELECT *
    FROM
    point_2d p1, point_2d p2
    WHERE p1.x <> p2.y
    

    But I prefere the first way because it more explicit and I think you can read better the query

    If you have some doubts I have found for you a list of operators used in SQL https://www.w3schools.com/sql/sql_operators.asp