Search code examples
sqljoinsyntaxwhere-clause

Difference between "on .. and" and "on .. where" in SQL Left Join?


Sql statement.

1.select a.* from A a left join B b on a.id =b.id and a.id=2;

2.select a.* from A a left join B b on a.id =b.id where a.id=2;

what is the difference of this two sql statement?


Solution

  • create table A(id int);
    create table B(id int);
    
    INSERT INTO A VALUES(1);
    INSERT INTO A VALUES(2);
    INSERT INTO A VALUES(3);
    
    INSERT INTO B VALUES(1);
    INSERT INTO B VALUES(2);
    INSERT INTO B VALUES(3);
    
    SELECT * FROM A;
    SELECT * FROM B;
    
    id
    -----------
    1
    2
    3
    
    id
    -----------
    1
    2
    3
    

    Filter on the JOIN to prevent rows from being added during the JOIN process.

    select a.*,b.*
    from   A a left join B b 
    on     a.id =b.id and a.id=2;
    
    id          id
    ----------- -----------
    1           NULL
    2           2
    3           NULL
    

    WHERE will filter after the JOIN has occurred.

    select a.*,b.* 
    from   A a left join B b 
    on     a.id =b.id 
    where  a.id=2;
    
    id          id
    ----------- -----------
    2           2