locked
Which join needs to be implement? RRS feed

  • Question

  • User1052662409 posted

    Hi All,

    Last week I was interviewed. The interviewer asked me a question regarding SQL.

    The question is below, you can easily understand by the image. here I have to tables, I need to find records which is uncommon in second table i.e. I need to find out the records which are colored by black color. See the image below.

    Thanks

    Thursday, July 28, 2016 5:31 AM

Answers

  • User1724605321 posted

    Hi Gaurav Kumar,

    You could use left join , suppose table 1 has id ,name , table B has id , name , you want to find all records from table2 also not exist in table 1 ,query below is for your reference :

    SELECT t2.name
    FROM table2 t2
    LEFT JOIN table1 t1 ON t1.name = t2.name
    WHERE t1.name IS NULL

    Or 

    SELECT name
    FROM table2
    WHERE name NOT IN
        (SELECT name 
         FROM table1)

    You could refer to below article for detail explaination :

    https://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/ 

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 28, 2016 5:40 AM