SQL - How to Return rows from left table not found in right table?












31















I have two tables with similar column names and I need to return records from the left table which are not found in the right table? I have a primary key(column) which will help me to compare both tables. Which join is preferred?










share|improve this question


















  • 1





    Seems quite a basic query... What have you tried so far ?

    – Laurent S.
    Sep 5 '14 at 12:09











  • use left outer join

    – Siva
    Sep 5 '14 at 12:11






  • 1





    @Siva Left outer join returns all the rows from the left table even if there are no matching records in the right table. I need to return matching records that are found in left table but not found in the right table.

    – CloudJedi
    Sep 5 '14 at 12:23











  • Are you still having issues with your query?

    – Kritner
    Sep 6 '14 at 18:04











  • stackoverflow.com/questions/406294/… Highly recommend checking out this answer.

    – Ciprianna Dudding
    Jan 18 '16 at 20:30
















31















I have two tables with similar column names and I need to return records from the left table which are not found in the right table? I have a primary key(column) which will help me to compare both tables. Which join is preferred?










share|improve this question


















  • 1





    Seems quite a basic query... What have you tried so far ?

    – Laurent S.
    Sep 5 '14 at 12:09











  • use left outer join

    – Siva
    Sep 5 '14 at 12:11






  • 1





    @Siva Left outer join returns all the rows from the left table even if there are no matching records in the right table. I need to return matching records that are found in left table but not found in the right table.

    – CloudJedi
    Sep 5 '14 at 12:23











  • Are you still having issues with your query?

    – Kritner
    Sep 6 '14 at 18:04











  • stackoverflow.com/questions/406294/… Highly recommend checking out this answer.

    – Ciprianna Dudding
    Jan 18 '16 at 20:30














31












31








31


6






I have two tables with similar column names and I need to return records from the left table which are not found in the right table? I have a primary key(column) which will help me to compare both tables. Which join is preferred?










share|improve this question














I have two tables with similar column names and I need to return records from the left table which are not found in the right table? I have a primary key(column) which will help me to compare both tables. Which join is preferred?







sql join left-join outer-join






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 5 '14 at 12:07









CloudJediCloudJedi

2802916




2802916








  • 1





    Seems quite a basic query... What have you tried so far ?

    – Laurent S.
    Sep 5 '14 at 12:09











  • use left outer join

    – Siva
    Sep 5 '14 at 12:11






  • 1





    @Siva Left outer join returns all the rows from the left table even if there are no matching records in the right table. I need to return matching records that are found in left table but not found in the right table.

    – CloudJedi
    Sep 5 '14 at 12:23











  • Are you still having issues with your query?

    – Kritner
    Sep 6 '14 at 18:04











  • stackoverflow.com/questions/406294/… Highly recommend checking out this answer.

    – Ciprianna Dudding
    Jan 18 '16 at 20:30














  • 1





    Seems quite a basic query... What have you tried so far ?

    – Laurent S.
    Sep 5 '14 at 12:09











  • use left outer join

    – Siva
    Sep 5 '14 at 12:11






  • 1





    @Siva Left outer join returns all the rows from the left table even if there are no matching records in the right table. I need to return matching records that are found in left table but not found in the right table.

    – CloudJedi
    Sep 5 '14 at 12:23











  • Are you still having issues with your query?

    – Kritner
    Sep 6 '14 at 18:04











  • stackoverflow.com/questions/406294/… Highly recommend checking out this answer.

    – Ciprianna Dudding
    Jan 18 '16 at 20:30








1




1





Seems quite a basic query... What have you tried so far ?

– Laurent S.
Sep 5 '14 at 12:09





Seems quite a basic query... What have you tried so far ?

– Laurent S.
Sep 5 '14 at 12:09













use left outer join

– Siva
Sep 5 '14 at 12:11





use left outer join

– Siva
Sep 5 '14 at 12:11




1




1





@Siva Left outer join returns all the rows from the left table even if there are no matching records in the right table. I need to return matching records that are found in left table but not found in the right table.

– CloudJedi
Sep 5 '14 at 12:23





@Siva Left outer join returns all the rows from the left table even if there are no matching records in the right table. I need to return matching records that are found in left table but not found in the right table.

– CloudJedi
Sep 5 '14 at 12:23













Are you still having issues with your query?

– Kritner
Sep 6 '14 at 18:04





Are you still having issues with your query?

– Kritner
Sep 6 '14 at 18:04













stackoverflow.com/questions/406294/… Highly recommend checking out this answer.

– Ciprianna Dudding
Jan 18 '16 at 20:30





stackoverflow.com/questions/406294/… Highly recommend checking out this answer.

– Ciprianna Dudding
Jan 18 '16 at 20:30












7 Answers
7






active

oldest

votes


















28














If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:




  1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.

  2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).


  3. Next comes the third type of joins, Outer Joins:



    In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.



    The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.




Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.






share|improve this answer

































    39














    Try This



    SELECT f.*
    FROM first_table f LEFT JOIN second_table s ON f.key=s.key
    WHERE s.key is NULL


    For more please read this article : Joins in Sql Server



    enter image description here






    share|improve this answer


























    • key is IS NULL not = NULL

      – Hayden Thring
      Mar 20 '17 at 3:41











    • @HaydenThring s.key = NULL means no matching row found in second table,so condition is true i think

      – Shamseer K
      Mar 22 '17 at 3:52











    • sorry i meant "the key to getting this to work is" not to be confused with use of "key" as a variable in this answer

      – Hayden Thring
      Mar 22 '17 at 5:37



















    4














    I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.



    SELECT Column1
    FROM TableA a
    WHERE NOT EXISTS ( SELECT Column1
    FROM Tableb b
    WHERE a.Column1 = b.Column1
    )





    share|improve this answer































      2














      I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).



      DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
      DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

      INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
      INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
      INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


      INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
      INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

      SELECT l.*
      FROM
      @testLeft l
      LEFT JOIN
      @testRight r ON
      l.ID = r.ID
      WHERE r.ID IS NULL





      share|improve this answer
























      • if you are using Mysql replace the last line WHERE r.ID IS NULL with WHERE ISNULL(r.ID)

        – Ananda
        Jul 24 '16 at 9:01





















      1














      This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.



      As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.



      Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/



      You're looking for a query such as:



      DECLARE @table1 TABLE (test int)
      DECLARE @table2 TABLE (test int)

      INSERT INTO @table1
      (
      test
      )
      SELECT 1
      UNION ALL SELECT 2

      INSERT INTO @table2
      (
      test
      )
      SELECT 1
      UNION ALL SELECT 3

      -- Here's the important part
      SELECT a.*
      FROM @table1 a
      LEFT join @table2 b on a.test = b.test -- this will return all rows from a
      WHERE b.test IS null -- this then excludes that which exist in both a and b

      -- Returned results:

      2





      share|improve this answer































        0














        This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.



        For me, the most understandable way I can think of is like so:



        --Users that bought from us 6 months ago and between 3 months ago.
        DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
        INSERT @6To3MonthsUsers
        select u.ID,opd.OrderDate
        from OrdersPaid opd
        inner join Orders o
        on opd.OrderID = o.ID
        inner join Users u
        on o.BuyerID = u.ID
        where 1=1
        and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())

        --Users that bought from us in the last 3 months
        DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
        INSERT @Last3MonthsUsers
        select u.ID,opd.OrderDate
        from OrdersPaid opd
        inner join Orders o
        on opd.OrderID = o.ID
        inner join Users u
        on o.BuyerID = u.ID
        where 1=1
        and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()


        Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.



        There are 2 simple ways to achieve that:





        1. Using Left Join:



          select distinct a.UserID
          from @6To3MonthsUsers a
          left join @Last3MonthsUsers b
          on a.UserID = b.UserID
          where b.UserID is null



        2. Not in:



          select distinct a.UserID
          from @6To3MonthsUsers a
          where a.UserID not in (select b.UserID from @Last3MonthsUsers b)



        Both ways will get me the same result, I personally prefer the second way because it's more readable.






        share|improve this answer

































          0














          select * from left table where key field not in (select key field from right table)






          share|improve this answer
























          • Can you post an explanation for why your code works? also use the formatting tools to better format your answer.

            – Mehdi
            Apr 12 '18 at 19:58











          • This is one of the correct ways to solve the question. But, its performance is not good if we work with 10k, 20k records

            – RDeveloper
            Nov 1 '18 at 8:29











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f25685545%2fsql-how-to-return-rows-from-left-table-not-found-in-right-table%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          28














          If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:




          1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.

          2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).


          3. Next comes the third type of joins, Outer Joins:



            In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.



            The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.




          Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.






          share|improve this answer






























            28














            If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:




            1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.

            2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).


            3. Next comes the third type of joins, Outer Joins:



              In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.



              The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.




            Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.






            share|improve this answer




























              28












              28








              28







              If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:




              1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.

              2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).


              3. Next comes the third type of joins, Outer Joins:



                In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.



                The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.




              Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.






              share|improve this answer















              If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:




              1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.

              2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).


              3. Next comes the third type of joins, Outer Joins:



                In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.



                The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.




              Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 29 '18 at 5:23









              ggorlen

              7,1203825




              7,1203825










              answered Sep 5 '14 at 12:25









              DeepshikhaDeepshikha

              7,08821318




              7,08821318

























                  39














                  Try This



                  SELECT f.*
                  FROM first_table f LEFT JOIN second_table s ON f.key=s.key
                  WHERE s.key is NULL


                  For more please read this article : Joins in Sql Server



                  enter image description here






                  share|improve this answer


























                  • key is IS NULL not = NULL

                    – Hayden Thring
                    Mar 20 '17 at 3:41











                  • @HaydenThring s.key = NULL means no matching row found in second table,so condition is true i think

                    – Shamseer K
                    Mar 22 '17 at 3:52











                  • sorry i meant "the key to getting this to work is" not to be confused with use of "key" as a variable in this answer

                    – Hayden Thring
                    Mar 22 '17 at 5:37
















                  39














                  Try This



                  SELECT f.*
                  FROM first_table f LEFT JOIN second_table s ON f.key=s.key
                  WHERE s.key is NULL


                  For more please read this article : Joins in Sql Server



                  enter image description here






                  share|improve this answer


























                  • key is IS NULL not = NULL

                    – Hayden Thring
                    Mar 20 '17 at 3:41











                  • @HaydenThring s.key = NULL means no matching row found in second table,so condition is true i think

                    – Shamseer K
                    Mar 22 '17 at 3:52











                  • sorry i meant "the key to getting this to work is" not to be confused with use of "key" as a variable in this answer

                    – Hayden Thring
                    Mar 22 '17 at 5:37














                  39












                  39








                  39







                  Try This



                  SELECT f.*
                  FROM first_table f LEFT JOIN second_table s ON f.key=s.key
                  WHERE s.key is NULL


                  For more please read this article : Joins in Sql Server



                  enter image description here






                  share|improve this answer















                  Try This



                  SELECT f.*
                  FROM first_table f LEFT JOIN second_table s ON f.key=s.key
                  WHERE s.key is NULL


                  For more please read this article : Joins in Sql Server



                  enter image description here







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Aug 12 '18 at 3:30

























                  answered Jun 25 '16 at 8:40









                  Shamseer KShamseer K

                  2,52111923




                  2,52111923













                  • key is IS NULL not = NULL

                    – Hayden Thring
                    Mar 20 '17 at 3:41











                  • @HaydenThring s.key = NULL means no matching row found in second table,so condition is true i think

                    – Shamseer K
                    Mar 22 '17 at 3:52











                  • sorry i meant "the key to getting this to work is" not to be confused with use of "key" as a variable in this answer

                    – Hayden Thring
                    Mar 22 '17 at 5:37



















                  • key is IS NULL not = NULL

                    – Hayden Thring
                    Mar 20 '17 at 3:41











                  • @HaydenThring s.key = NULL means no matching row found in second table,so condition is true i think

                    – Shamseer K
                    Mar 22 '17 at 3:52











                  • sorry i meant "the key to getting this to work is" not to be confused with use of "key" as a variable in this answer

                    – Hayden Thring
                    Mar 22 '17 at 5:37

















                  key is IS NULL not = NULL

                  – Hayden Thring
                  Mar 20 '17 at 3:41





                  key is IS NULL not = NULL

                  – Hayden Thring
                  Mar 20 '17 at 3:41













                  @HaydenThring s.key = NULL means no matching row found in second table,so condition is true i think

                  – Shamseer K
                  Mar 22 '17 at 3:52





                  @HaydenThring s.key = NULL means no matching row found in second table,so condition is true i think

                  – Shamseer K
                  Mar 22 '17 at 3:52













                  sorry i meant "the key to getting this to work is" not to be confused with use of "key" as a variable in this answer

                  – Hayden Thring
                  Mar 22 '17 at 5:37





                  sorry i meant "the key to getting this to work is" not to be confused with use of "key" as a variable in this answer

                  – Hayden Thring
                  Mar 22 '17 at 5:37











                  4














                  I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.



                  SELECT Column1
                  FROM TableA a
                  WHERE NOT EXISTS ( SELECT Column1
                  FROM Tableb b
                  WHERE a.Column1 = b.Column1
                  )





                  share|improve this answer




























                    4














                    I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.



                    SELECT Column1
                    FROM TableA a
                    WHERE NOT EXISTS ( SELECT Column1
                    FROM Tableb b
                    WHERE a.Column1 = b.Column1
                    )





                    share|improve this answer


























                      4












                      4








                      4







                      I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.



                      SELECT Column1
                      FROM TableA a
                      WHERE NOT EXISTS ( SELECT Column1
                      FROM Tableb b
                      WHERE a.Column1 = b.Column1
                      )





                      share|improve this answer













                      I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.



                      SELECT Column1
                      FROM TableA a
                      WHERE NOT EXISTS ( SELECT Column1
                      FROM Tableb b
                      WHERE a.Column1 = b.Column1
                      )






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 26 '16 at 14:38









                      viejoEngineerviejoEngineer

                      1248




                      1248























                          2














                          I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).



                          DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
                          DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

                          INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

                          SELECT l.*
                          FROM
                          @testLeft l
                          LEFT JOIN
                          @testRight r ON
                          l.ID = r.ID
                          WHERE r.ID IS NULL





                          share|improve this answer
























                          • if you are using Mysql replace the last line WHERE r.ID IS NULL with WHERE ISNULL(r.ID)

                            – Ananda
                            Jul 24 '16 at 9:01


















                          2














                          I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).



                          DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
                          DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

                          INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

                          SELECT l.*
                          FROM
                          @testLeft l
                          LEFT JOIN
                          @testRight r ON
                          l.ID = r.ID
                          WHERE r.ID IS NULL





                          share|improve this answer
























                          • if you are using Mysql replace the last line WHERE r.ID IS NULL with WHERE ISNULL(r.ID)

                            – Ananda
                            Jul 24 '16 at 9:01
















                          2












                          2








                          2







                          I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).



                          DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
                          DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

                          INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

                          SELECT l.*
                          FROM
                          @testLeft l
                          LEFT JOIN
                          @testRight r ON
                          l.ID = r.ID
                          WHERE r.ID IS NULL





                          share|improve this answer













                          I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).



                          DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
                          DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

                          INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
                          INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
                          INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

                          SELECT l.*
                          FROM
                          @testLeft l
                          LEFT JOIN
                          @testRight r ON
                          l.ID = r.ID
                          WHERE r.ID IS NULL






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 5 '14 at 13:02









                          AHigginsAHiggins

                          6,04462542




                          6,04462542













                          • if you are using Mysql replace the last line WHERE r.ID IS NULL with WHERE ISNULL(r.ID)

                            – Ananda
                            Jul 24 '16 at 9:01





















                          • if you are using Mysql replace the last line WHERE r.ID IS NULL with WHERE ISNULL(r.ID)

                            – Ananda
                            Jul 24 '16 at 9:01



















                          if you are using Mysql replace the last line WHERE r.ID IS NULL with WHERE ISNULL(r.ID)

                          – Ananda
                          Jul 24 '16 at 9:01







                          if you are using Mysql replace the last line WHERE r.ID IS NULL with WHERE ISNULL(r.ID)

                          – Ananda
                          Jul 24 '16 at 9:01













                          1














                          This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.



                          As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.



                          Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/



                          You're looking for a query such as:



                          DECLARE @table1 TABLE (test int)
                          DECLARE @table2 TABLE (test int)

                          INSERT INTO @table1
                          (
                          test
                          )
                          SELECT 1
                          UNION ALL SELECT 2

                          INSERT INTO @table2
                          (
                          test
                          )
                          SELECT 1
                          UNION ALL SELECT 3

                          -- Here's the important part
                          SELECT a.*
                          FROM @table1 a
                          LEFT join @table2 b on a.test = b.test -- this will return all rows from a
                          WHERE b.test IS null -- this then excludes that which exist in both a and b

                          -- Returned results:

                          2





                          share|improve this answer




























                            1














                            This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.



                            As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.



                            Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/



                            You're looking for a query such as:



                            DECLARE @table1 TABLE (test int)
                            DECLARE @table2 TABLE (test int)

                            INSERT INTO @table1
                            (
                            test
                            )
                            SELECT 1
                            UNION ALL SELECT 2

                            INSERT INTO @table2
                            (
                            test
                            )
                            SELECT 1
                            UNION ALL SELECT 3

                            -- Here's the important part
                            SELECT a.*
                            FROM @table1 a
                            LEFT join @table2 b on a.test = b.test -- this will return all rows from a
                            WHERE b.test IS null -- this then excludes that which exist in both a and b

                            -- Returned results:

                            2





                            share|improve this answer


























                              1












                              1








                              1







                              This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.



                              As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.



                              Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/



                              You're looking for a query such as:



                              DECLARE @table1 TABLE (test int)
                              DECLARE @table2 TABLE (test int)

                              INSERT INTO @table1
                              (
                              test
                              )
                              SELECT 1
                              UNION ALL SELECT 2

                              INSERT INTO @table2
                              (
                              test
                              )
                              SELECT 1
                              UNION ALL SELECT 3

                              -- Here's the important part
                              SELECT a.*
                              FROM @table1 a
                              LEFT join @table2 b on a.test = b.test -- this will return all rows from a
                              WHERE b.test IS null -- this then excludes that which exist in both a and b

                              -- Returned results:

                              2





                              share|improve this answer













                              This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.



                              As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.



                              Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/



                              You're looking for a query such as:



                              DECLARE @table1 TABLE (test int)
                              DECLARE @table2 TABLE (test int)

                              INSERT INTO @table1
                              (
                              test
                              )
                              SELECT 1
                              UNION ALL SELECT 2

                              INSERT INTO @table2
                              (
                              test
                              )
                              SELECT 1
                              UNION ALL SELECT 3

                              -- Here's the important part
                              SELECT a.*
                              FROM @table1 a
                              LEFT join @table2 b on a.test = b.test -- this will return all rows from a
                              WHERE b.test IS null -- this then excludes that which exist in both a and b

                              -- Returned results:

                              2






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Sep 5 '14 at 12:24









                              KritnerKritner

                              10.3k73256




                              10.3k73256























                                  0














                                  This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.



                                  For me, the most understandable way I can think of is like so:



                                  --Users that bought from us 6 months ago and between 3 months ago.
                                  DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
                                  INSERT @6To3MonthsUsers
                                  select u.ID,opd.OrderDate
                                  from OrdersPaid opd
                                  inner join Orders o
                                  on opd.OrderID = o.ID
                                  inner join Users u
                                  on o.BuyerID = u.ID
                                  where 1=1
                                  and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())

                                  --Users that bought from us in the last 3 months
                                  DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
                                  INSERT @Last3MonthsUsers
                                  select u.ID,opd.OrderDate
                                  from OrdersPaid opd
                                  inner join Orders o
                                  on opd.OrderID = o.ID
                                  inner join Users u
                                  on o.BuyerID = u.ID
                                  where 1=1
                                  and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()


                                  Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.



                                  There are 2 simple ways to achieve that:





                                  1. Using Left Join:



                                    select distinct a.UserID
                                    from @6To3MonthsUsers a
                                    left join @Last3MonthsUsers b
                                    on a.UserID = b.UserID
                                    where b.UserID is null



                                  2. Not in:



                                    select distinct a.UserID
                                    from @6To3MonthsUsers a
                                    where a.UserID not in (select b.UserID from @Last3MonthsUsers b)



                                  Both ways will get me the same result, I personally prefer the second way because it's more readable.






                                  share|improve this answer






























                                    0














                                    This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.



                                    For me, the most understandable way I can think of is like so:



                                    --Users that bought from us 6 months ago and between 3 months ago.
                                    DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
                                    INSERT @6To3MonthsUsers
                                    select u.ID,opd.OrderDate
                                    from OrdersPaid opd
                                    inner join Orders o
                                    on opd.OrderID = o.ID
                                    inner join Users u
                                    on o.BuyerID = u.ID
                                    where 1=1
                                    and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())

                                    --Users that bought from us in the last 3 months
                                    DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
                                    INSERT @Last3MonthsUsers
                                    select u.ID,opd.OrderDate
                                    from OrdersPaid opd
                                    inner join Orders o
                                    on opd.OrderID = o.ID
                                    inner join Users u
                                    on o.BuyerID = u.ID
                                    where 1=1
                                    and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()


                                    Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.



                                    There are 2 simple ways to achieve that:





                                    1. Using Left Join:



                                      select distinct a.UserID
                                      from @6To3MonthsUsers a
                                      left join @Last3MonthsUsers b
                                      on a.UserID = b.UserID
                                      where b.UserID is null



                                    2. Not in:



                                      select distinct a.UserID
                                      from @6To3MonthsUsers a
                                      where a.UserID not in (select b.UserID from @Last3MonthsUsers b)



                                    Both ways will get me the same result, I personally prefer the second way because it's more readable.






                                    share|improve this answer




























                                      0












                                      0








                                      0







                                      This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.



                                      For me, the most understandable way I can think of is like so:



                                      --Users that bought from us 6 months ago and between 3 months ago.
                                      DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
                                      INSERT @6To3MonthsUsers
                                      select u.ID,opd.OrderDate
                                      from OrdersPaid opd
                                      inner join Orders o
                                      on opd.OrderID = o.ID
                                      inner join Users u
                                      on o.BuyerID = u.ID
                                      where 1=1
                                      and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())

                                      --Users that bought from us in the last 3 months
                                      DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
                                      INSERT @Last3MonthsUsers
                                      select u.ID,opd.OrderDate
                                      from OrdersPaid opd
                                      inner join Orders o
                                      on opd.OrderID = o.ID
                                      inner join Users u
                                      on o.BuyerID = u.ID
                                      where 1=1
                                      and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()


                                      Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.



                                      There are 2 simple ways to achieve that:





                                      1. Using Left Join:



                                        select distinct a.UserID
                                        from @6To3MonthsUsers a
                                        left join @Last3MonthsUsers b
                                        on a.UserID = b.UserID
                                        where b.UserID is null



                                      2. Not in:



                                        select distinct a.UserID
                                        from @6To3MonthsUsers a
                                        where a.UserID not in (select b.UserID from @Last3MonthsUsers b)



                                      Both ways will get me the same result, I personally prefer the second way because it's more readable.






                                      share|improve this answer















                                      This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.



                                      For me, the most understandable way I can think of is like so:



                                      --Users that bought from us 6 months ago and between 3 months ago.
                                      DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
                                      INSERT @6To3MonthsUsers
                                      select u.ID,opd.OrderDate
                                      from OrdersPaid opd
                                      inner join Orders o
                                      on opd.OrderID = o.ID
                                      inner join Users u
                                      on o.BuyerID = u.ID
                                      where 1=1
                                      and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())

                                      --Users that bought from us in the last 3 months
                                      DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
                                      INSERT @Last3MonthsUsers
                                      select u.ID,opd.OrderDate
                                      from OrdersPaid opd
                                      inner join Orders o
                                      on opd.OrderID = o.ID
                                      inner join Users u
                                      on o.BuyerID = u.ID
                                      where 1=1
                                      and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()


                                      Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.



                                      There are 2 simple ways to achieve that:





                                      1. Using Left Join:



                                        select distinct a.UserID
                                        from @6To3MonthsUsers a
                                        left join @Last3MonthsUsers b
                                        on a.UserID = b.UserID
                                        where b.UserID is null



                                      2. Not in:



                                        select distinct a.UserID
                                        from @6To3MonthsUsers a
                                        where a.UserID not in (select b.UserID from @Last3MonthsUsers b)



                                      Both ways will get me the same result, I personally prefer the second way because it's more readable.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Oct 3 '17 at 8:28

























                                      answered Oct 3 '17 at 6:52









                                      Offir Pe'erOffir Pe'er

                                      1,8931536




                                      1,8931536























                                          0














                                          select * from left table where key field not in (select key field from right table)






                                          share|improve this answer
























                                          • Can you post an explanation for why your code works? also use the formatting tools to better format your answer.

                                            – Mehdi
                                            Apr 12 '18 at 19:58











                                          • This is one of the correct ways to solve the question. But, its performance is not good if we work with 10k, 20k records

                                            – RDeveloper
                                            Nov 1 '18 at 8:29
















                                          0














                                          select * from left table where key field not in (select key field from right table)






                                          share|improve this answer
























                                          • Can you post an explanation for why your code works? also use the formatting tools to better format your answer.

                                            – Mehdi
                                            Apr 12 '18 at 19:58











                                          • This is one of the correct ways to solve the question. But, its performance is not good if we work with 10k, 20k records

                                            – RDeveloper
                                            Nov 1 '18 at 8:29














                                          0












                                          0








                                          0







                                          select * from left table where key field not in (select key field from right table)






                                          share|improve this answer













                                          select * from left table where key field not in (select key field from right table)







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Apr 12 '18 at 19:39









                                          George LetGeorge Let

                                          1




                                          1













                                          • Can you post an explanation for why your code works? also use the formatting tools to better format your answer.

                                            – Mehdi
                                            Apr 12 '18 at 19:58











                                          • This is one of the correct ways to solve the question. But, its performance is not good if we work with 10k, 20k records

                                            – RDeveloper
                                            Nov 1 '18 at 8:29



















                                          • Can you post an explanation for why your code works? also use the formatting tools to better format your answer.

                                            – Mehdi
                                            Apr 12 '18 at 19:58











                                          • This is one of the correct ways to solve the question. But, its performance is not good if we work with 10k, 20k records

                                            – RDeveloper
                                            Nov 1 '18 at 8:29

















                                          Can you post an explanation for why your code works? also use the formatting tools to better format your answer.

                                          – Mehdi
                                          Apr 12 '18 at 19:58





                                          Can you post an explanation for why your code works? also use the formatting tools to better format your answer.

                                          – Mehdi
                                          Apr 12 '18 at 19:58













                                          This is one of the correct ways to solve the question. But, its performance is not good if we work with 10k, 20k records

                                          – RDeveloper
                                          Nov 1 '18 at 8:29





                                          This is one of the correct ways to solve the question. But, its performance is not good if we work with 10k, 20k records

                                          – RDeveloper
                                          Nov 1 '18 at 8:29


















                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f25685545%2fsql-how-to-return-rows-from-left-table-not-found-in-right-table%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Mossoró

                                          Cannot access a disposed object : DataContext

                                          Can't read property showImagePicker of undefined in react native iOS