SQL Server (JOIN) all from first with NULLs from 2ndSQL Server Query: Inefficient where clauseSQL join query to show rows with non-existent rows in one tableOUTER JOIN with join condition causes unexpected resultsCheck for existing matches to find the field their grouped-bystats_date is nullPerformance gap between WHERE IN (1,2,3,4) vs IN (select * from STRING_SPLIT('1,2,3,4',','))Difference between two tablesSQL Server 2016 ISNULL Returning 1900-01-01How to perform JOIN and only use single record for each instance on 2nd tableDynamic SQL - How can you use it to run a SELECT against all schema's and Tables?

Can a user sell my software (MIT license) without modification?

Why is quantum entanglement surprising?

How is TD(0) method helpful? What good does it do?

Can a magnetic field of an object be stronger than its gravity?

Incremental Ranges!

C SIGINT signal in Linux

How can drunken, homicidal elves successfully conduct a wild hunt?

Etymology of 'calcit(r)are'?

Why did Hela need Heimdal's sword?

How can this map be coloured using four colours?

How bad would a partial hash leak be, realistically?

Why did a party with more votes get fewer seats in the 2019 European Parliament election in Denmark?

Aligning object in a commutative diagram

Credit card offering 0.5 miles for every cent rounded up. Too good to be true?

Whats the next step after commercial fusion reactors?

Why don't B747s start takeoffs with full throttle?

Building a road to escape Earth's gravity by making a pyramid on Antartica

Does an ice chest packed full of frozen food need ice? 18 day Grand Canyon trip

Sharing one invocation list between multiple events on the same object in C#

Company did not petition for visa in a timely manner. Is asking me to work from overseas, but wants me to take a paycut

PhD student with mental health issues and bad performance

Importance sampling estimation of power function

Did thousands of women die every year due to illegal abortions before Roe v. Wade?

What is in `tex.print` or `tex.sprint`?



SQL Server (JOIN) all from first with NULLs from 2nd


SQL Server Query: Inefficient where clauseSQL join query to show rows with non-existent rows in one tableOUTER JOIN with join condition causes unexpected resultsCheck for existing matches to find the field their grouped-bystats_date is nullPerformance gap between WHERE IN (1,2,3,4) vs IN (select * from STRING_SPLIT('1,2,3,4',','))Difference between two tablesSQL Server 2016 ISNULL Returning 1900-01-01How to perform JOIN and only use single record for each instance on 2nd tableDynamic SQL - How can you use it to run a SELECT against all schema's and Tables?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















I have 2 tables (Reps and DailyStartTimes).
the Rep Table returns 37 rows, but when I Join it with the 2nd table I get 36 rows as the 2nd table only has 36 rows that match the first table. How do I go about getting the 37 rows back with a Null result for the row that was not matched?



Here is the query that I have so far



SELECT 
tblReps.[sName] AS 'RepName',
tblReps.sNote AS 'Type',
RIGHT(CAST(tblDaily.sDateAndTimeStart AS smalldatetime), 8) AS 'DayStarted'

FROM
[tblRepresentatives] AS tblReps

FULL OUTER JOIN
tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode

WHERE
tblDaily.sDate = CAST(GETDATE() AS DATE)
AND tblReps.[sActive] = 'True'









share|improve this question







New contributor



Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    3















    I have 2 tables (Reps and DailyStartTimes).
    the Rep Table returns 37 rows, but when I Join it with the 2nd table I get 36 rows as the 2nd table only has 36 rows that match the first table. How do I go about getting the 37 rows back with a Null result for the row that was not matched?



    Here is the query that I have so far



    SELECT 
    tblReps.[sName] AS 'RepName',
    tblReps.sNote AS 'Type',
    RIGHT(CAST(tblDaily.sDateAndTimeStart AS smalldatetime), 8) AS 'DayStarted'

    FROM
    [tblRepresentatives] AS tblReps

    FULL OUTER JOIN
    tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode

    WHERE
    tblDaily.sDate = CAST(GETDATE() AS DATE)
    AND tblReps.[sActive] = 'True'









    share|improve this question







    New contributor



    Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





















      3












      3








      3


      1






      I have 2 tables (Reps and DailyStartTimes).
      the Rep Table returns 37 rows, but when I Join it with the 2nd table I get 36 rows as the 2nd table only has 36 rows that match the first table. How do I go about getting the 37 rows back with a Null result for the row that was not matched?



      Here is the query that I have so far



      SELECT 
      tblReps.[sName] AS 'RepName',
      tblReps.sNote AS 'Type',
      RIGHT(CAST(tblDaily.sDateAndTimeStart AS smalldatetime), 8) AS 'DayStarted'

      FROM
      [tblRepresentatives] AS tblReps

      FULL OUTER JOIN
      tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode

      WHERE
      tblDaily.sDate = CAST(GETDATE() AS DATE)
      AND tblReps.[sActive] = 'True'









      share|improve this question







      New contributor



      Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I have 2 tables (Reps and DailyStartTimes).
      the Rep Table returns 37 rows, but when I Join it with the 2nd table I get 36 rows as the 2nd table only has 36 rows that match the first table. How do I go about getting the 37 rows back with a Null result for the row that was not matched?



      Here is the query that I have so far



      SELECT 
      tblReps.[sName] AS 'RepName',
      tblReps.sNote AS 'Type',
      RIGHT(CAST(tblDaily.sDateAndTimeStart AS smalldatetime), 8) AS 'DayStarted'

      FROM
      [tblRepresentatives] AS tblReps

      FULL OUTER JOIN
      tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode

      WHERE
      tblDaily.sDate = CAST(GETDATE() AS DATE)
      AND tblReps.[sActive] = 'True'






      sql-server






      share|improve this question







      New contributor



      Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share|improve this question







      New contributor



      Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share|improve this question




      share|improve this question






      New contributor



      Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      asked May 27 at 13:06









      Mark BlackburnMark Blackburn

      182




      182




      New contributor



      Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




      New contributor




      Mark Blackburn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          4














          First of all, the correct type of join to use in this case is a left join:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          ...


          In your specific case, you could still use FULL because this condition in WHERE would turn it into a left join anyway:



          tblReps.[sActive] = 'True'


          But it is better to express the intent accurately.



          The same effect that turns your full join into a left join is actually responsible for the missing 37th row that you expected. More specifically, this other WHERE condition:



          tblDaily.sDate = CAST(GETDATE() AS DATE)


          transforms your join further into an inner join. That is why the 37th row is missing from the output.



          The reason for that happening is this. The FROM clause returns a null in tblDaily.sDate for the unmatched row. Because the WHERE clause logically executes after the FROM, the above-mentioned predicate excludes the unmatched row, since NULL = CAST(GETDATE() AS DATE) does not evaluate to True.



          What you need to do instead is move the sDate condition to the ON subclause:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          AND tblDaily.sDate = CAST(GETDATE() AS DATE)

          WHERE
          tblReps.[sActive] = 'True'


          That way the right-hand side of the join is filtered on tblDaily.sDate = CAST(GETDATE() AS DATE) before the join takes place. Consequently, the query will return the expected 37 rows from tblReps complemented either with matching data from tblDaily or with nulls.






          share|improve this answer

























          • Thank you, Andriy that explanation was very helpful and makes sense to me. I have tested and I am now getting the expected result.

            – Mark Blackburn
            May 27 at 14:26











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "182"
          ;
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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
          );



          );






          Mark Blackburn is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f239140%2fsql-server-join-all-from-first-with-nulls-from-2nd%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          First of all, the correct type of join to use in this case is a left join:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          ...


          In your specific case, you could still use FULL because this condition in WHERE would turn it into a left join anyway:



          tblReps.[sActive] = 'True'


          But it is better to express the intent accurately.



          The same effect that turns your full join into a left join is actually responsible for the missing 37th row that you expected. More specifically, this other WHERE condition:



          tblDaily.sDate = CAST(GETDATE() AS DATE)


          transforms your join further into an inner join. That is why the 37th row is missing from the output.



          The reason for that happening is this. The FROM clause returns a null in tblDaily.sDate for the unmatched row. Because the WHERE clause logically executes after the FROM, the above-mentioned predicate excludes the unmatched row, since NULL = CAST(GETDATE() AS DATE) does not evaluate to True.



          What you need to do instead is move the sDate condition to the ON subclause:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          AND tblDaily.sDate = CAST(GETDATE() AS DATE)

          WHERE
          tblReps.[sActive] = 'True'


          That way the right-hand side of the join is filtered on tblDaily.sDate = CAST(GETDATE() AS DATE) before the join takes place. Consequently, the query will return the expected 37 rows from tblReps complemented either with matching data from tblDaily or with nulls.






          share|improve this answer

























          • Thank you, Andriy that explanation was very helpful and makes sense to me. I have tested and I am now getting the expected result.

            – Mark Blackburn
            May 27 at 14:26















          4














          First of all, the correct type of join to use in this case is a left join:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          ...


          In your specific case, you could still use FULL because this condition in WHERE would turn it into a left join anyway:



          tblReps.[sActive] = 'True'


          But it is better to express the intent accurately.



          The same effect that turns your full join into a left join is actually responsible for the missing 37th row that you expected. More specifically, this other WHERE condition:



          tblDaily.sDate = CAST(GETDATE() AS DATE)


          transforms your join further into an inner join. That is why the 37th row is missing from the output.



          The reason for that happening is this. The FROM clause returns a null in tblDaily.sDate for the unmatched row. Because the WHERE clause logically executes after the FROM, the above-mentioned predicate excludes the unmatched row, since NULL = CAST(GETDATE() AS DATE) does not evaluate to True.



          What you need to do instead is move the sDate condition to the ON subclause:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          AND tblDaily.sDate = CAST(GETDATE() AS DATE)

          WHERE
          tblReps.[sActive] = 'True'


          That way the right-hand side of the join is filtered on tblDaily.sDate = CAST(GETDATE() AS DATE) before the join takes place. Consequently, the query will return the expected 37 rows from tblReps complemented either with matching data from tblDaily or with nulls.






          share|improve this answer

























          • Thank you, Andriy that explanation was very helpful and makes sense to me. I have tested and I am now getting the expected result.

            – Mark Blackburn
            May 27 at 14:26













          4












          4








          4







          First of all, the correct type of join to use in this case is a left join:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          ...


          In your specific case, you could still use FULL because this condition in WHERE would turn it into a left join anyway:



          tblReps.[sActive] = 'True'


          But it is better to express the intent accurately.



          The same effect that turns your full join into a left join is actually responsible for the missing 37th row that you expected. More specifically, this other WHERE condition:



          tblDaily.sDate = CAST(GETDATE() AS DATE)


          transforms your join further into an inner join. That is why the 37th row is missing from the output.



          The reason for that happening is this. The FROM clause returns a null in tblDaily.sDate for the unmatched row. Because the WHERE clause logically executes after the FROM, the above-mentioned predicate excludes the unmatched row, since NULL = CAST(GETDATE() AS DATE) does not evaluate to True.



          What you need to do instead is move the sDate condition to the ON subclause:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          AND tblDaily.sDate = CAST(GETDATE() AS DATE)

          WHERE
          tblReps.[sActive] = 'True'


          That way the right-hand side of the join is filtered on tblDaily.sDate = CAST(GETDATE() AS DATE) before the join takes place. Consequently, the query will return the expected 37 rows from tblReps complemented either with matching data from tblDaily or with nulls.






          share|improve this answer















          First of all, the correct type of join to use in this case is a left join:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          ...


          In your specific case, you could still use FULL because this condition in WHERE would turn it into a left join anyway:



          tblReps.[sActive] = 'True'


          But it is better to express the intent accurately.



          The same effect that turns your full join into a left join is actually responsible for the missing 37th row that you expected. More specifically, this other WHERE condition:



          tblDaily.sDate = CAST(GETDATE() AS DATE)


          transforms your join further into an inner join. That is why the 37th row is missing from the output.



          The reason for that happening is this. The FROM clause returns a null in tblDaily.sDate for the unmatched row. Because the WHERE clause logically executes after the FROM, the above-mentioned predicate excludes the unmatched row, since NULL = CAST(GETDATE() AS DATE) does not evaluate to True.



          What you need to do instead is move the sDate condition to the ON subclause:



          ...
          FROM
          [tblRepresentatives] AS tblReps

          LEFT OUTER JOIN
          tblDailyWorkingTime AS tblDaily ON tblDaily.sRepresentativeCode = tblReps.sCode
          AND tblDaily.sDate = CAST(GETDATE() AS DATE)

          WHERE
          tblReps.[sActive] = 'True'


          That way the right-hand side of the join is filtered on tblDaily.sDate = CAST(GETDATE() AS DATE) before the join takes place. Consequently, the query will return the expected 37 rows from tblReps complemented either with matching data from tblDaily or with nulls.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 27 at 16:13

























          answered May 27 at 13:39









          Andriy MAndriy M

          16.6k63777




          16.6k63777












          • Thank you, Andriy that explanation was very helpful and makes sense to me. I have tested and I am now getting the expected result.

            – Mark Blackburn
            May 27 at 14:26

















          • Thank you, Andriy that explanation was very helpful and makes sense to me. I have tested and I am now getting the expected result.

            – Mark Blackburn
            May 27 at 14:26
















          Thank you, Andriy that explanation was very helpful and makes sense to me. I have tested and I am now getting the expected result.

          – Mark Blackburn
          May 27 at 14:26





          Thank you, Andriy that explanation was very helpful and makes sense to me. I have tested and I am now getting the expected result.

          – Mark Blackburn
          May 27 at 14:26










          Mark Blackburn is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          Mark Blackburn is a new contributor. Be nice, and check out our Code of Conduct.












          Mark Blackburn is a new contributor. Be nice, and check out our Code of Conduct.











          Mark Blackburn is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Database Administrators Stack Exchange!


          • 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%2fdba.stackexchange.com%2fquestions%2f239140%2fsql-server-join-all-from-first-with-nulls-from-2nd%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

          Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form