Where statement Hierarchy for Selecting rows The Next CEO of Stack OverflowSelect columns from result set of stored procedureCan I concatenate multiple MySQL rows into one field?How do I limit the number of rows returned by an Oracle query after ordering?Select n random rows from SQL Server tableWhen should I use cross apply over inner join?Best way to test if a row exists in a MySQL tableSQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?What are the options for storing hierarchical data in a relational database?Create a temporary table in a SELECT statement without a separate CREATE TABLE

Ising model simulation

Calculate the Mean mean of two numbers

My ex-girlfriend uses my Apple ID to login to her iPad, do I have to give her my Apple ID password to reset it?

How dangerous is XSS

How to show a landlord what we have in savings?

What does it mean 'exit 1' for a job status after rclone sync

Upgrading From a 9 Speed Sora Derailleur?

Shortening a title without changing its meaning

How to find if SQL server backup is encrypted with TDE without restoring the backup

Does int main() need a declaration on C++?

How exploitable/balanced is this homebrew spell: Spell Permanency?

Direct Implications Between USA and UK in Event of No-Deal Brexit

Does Germany produce more waste than the US?

Read/write a pipe-delimited file line by line with some simple text manipulation

Car headlights in a world without electricity

Simplify trigonometric expression using trigonometric identities

What is the difference between 'contrib' and 'non-free' packages repositories?

Compensation for working overtime on Saturdays

How should I connect my cat5 cable to connectors having an orange-green line?

How seriously should I take size and weight limits of hand luggage?

Is it possible to create a QR code using text?

Why can't we say "I have been having a dog"?

Prodigo = pro + ago?

Can a PhD from a non-TU9 German university become a professor in a TU9 university?



Where statement Hierarchy for Selecting rows



The Next CEO of Stack OverflowSelect columns from result set of stored procedureCan I concatenate multiple MySQL rows into one field?How do I limit the number of rows returned by an Oracle query after ordering?Select n random rows from SQL Server tableWhen should I use cross apply over inner join?Best way to test if a row exists in a MySQL tableSQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?What are the options for storing hierarchical data in a relational database?Create a temporary table in a SELECT statement without a separate CREATE TABLE










0















I have a table with a column called ReportTypeId. I want to select rows where ReportTypeId = 1, but if no rows exist for this, then I want ReportTypeId = 2. I am trying to use a WHEN EXISTS, but I cannot figure out how to select more then one column. I want to write a query that looks something like this:



SELECT CASE 
WHEN EXISTS (SELECT PerformanceReport FROM ReportData
WHERE (ReportId = 79 and ReportTypeId = 1))

THEN (select * from ReferenceData
where ReportTypeId = 1)

ELSE (select * from ReferenceData
where ReportTypeId = 2)
END


But because I am trying to return more than one column it doesn't work. Is there a way to create a query that bases it's WHERE statement based on whether the data exists or not?










share|improve this question


























    0















    I have a table with a column called ReportTypeId. I want to select rows where ReportTypeId = 1, but if no rows exist for this, then I want ReportTypeId = 2. I am trying to use a WHEN EXISTS, but I cannot figure out how to select more then one column. I want to write a query that looks something like this:



    SELECT CASE 
    WHEN EXISTS (SELECT PerformanceReport FROM ReportData
    WHERE (ReportId = 79 and ReportTypeId = 1))

    THEN (select * from ReferenceData
    where ReportTypeId = 1)

    ELSE (select * from ReferenceData
    where ReportTypeId = 2)
    END


    But because I am trying to return more than one column it doesn't work. Is there a way to create a query that bases it's WHERE statement based on whether the data exists or not?










    share|improve this question
























      0












      0








      0








      I have a table with a column called ReportTypeId. I want to select rows where ReportTypeId = 1, but if no rows exist for this, then I want ReportTypeId = 2. I am trying to use a WHEN EXISTS, but I cannot figure out how to select more then one column. I want to write a query that looks something like this:



      SELECT CASE 
      WHEN EXISTS (SELECT PerformanceReport FROM ReportData
      WHERE (ReportId = 79 and ReportTypeId = 1))

      THEN (select * from ReferenceData
      where ReportTypeId = 1)

      ELSE (select * from ReferenceData
      where ReportTypeId = 2)
      END


      But because I am trying to return more than one column it doesn't work. Is there a way to create a query that bases it's WHERE statement based on whether the data exists or not?










      share|improve this question














      I have a table with a column called ReportTypeId. I want to select rows where ReportTypeId = 1, but if no rows exist for this, then I want ReportTypeId = 2. I am trying to use a WHEN EXISTS, but I cannot figure out how to select more then one column. I want to write a query that looks something like this:



      SELECT CASE 
      WHEN EXISTS (SELECT PerformanceReport FROM ReportData
      WHERE (ReportId = 79 and ReportTypeId = 1))

      THEN (select * from ReferenceData
      where ReportTypeId = 1)

      ELSE (select * from ReferenceData
      where ReportTypeId = 2)
      END


      But because I am trying to return more than one column it doesn't work. Is there a way to create a query that bases it's WHERE statement based on whether the data exists or not?







      sql select exists case-when






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 19:13









      MwspencerMwspencer

      355116




      355116






















          3 Answers
          3






          active

          oldest

          votes


















          1














          If RecordTypeId can be ordered**, then you can use the following



          SELECT PerformanceReport 
          FROM ReferenceData
          WHERE ReportTypeId = (
          SELECT MIN(ReportTypeId)
          FROM ReportData
          WHERE ReportTypeId IN (1, 2)
          AND ReportId = 79
          )


          ** by ordered, I mean that the MIN aggregate function will return the expected result. For integers this makes sense, however, if your report type ids are text uuids, then MIN would still work but won't give you the expected result, because it will return the minimum id in lexical order.






          share|improve this answer




















          • 1





            This works great for my case, but I can see that if ReportTypeId = 2 becomes the priority over 1, but not as import as say 3 (2 > 1 > 3), then I'm guessing I'm out of luck?... Well I guess I can create a temp table that would assign a rank of importance, so actually yes I really like this solution, thanks!

            – Mwspencer
            Mar 8 at 19:30












          • @Mwspencer . . . I am baffled at how this answer can be accepted when it does not even seem to be selecting from the correct table.

            – Gordon Linoff
            Mar 8 at 19:46











          • @GordonLinoff, thanks for catching that error!

            – Haleemur Ali
            Mar 8 at 21:32











          • @GordonLinoff, I think it's the idea more than the hard code that I am accepting. As my actual user case is a bit more complicated than my question, and this answer helped created the most straightforward solution. I will admit I have not tested for performance though as that is not important to my specific case. All answers gave the correct output, but this one took the least amount of code.

            – Mwspencer
            Mar 11 at 15:11


















          1














          You can use the following solution:



          SELECT * 
          FROM ReferenceData
          WHERE (
          ReportTypeId = 1
          AND EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
          ) OR (
          ReportTypeId = 2
          AND NOT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
          )


          You can optimize this with a JOIN:



          SELECT ReferenceData.* 
          FROM ReferenceData JOIN (
          SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
          ) isAvailable
          WHERE (
          ReportTypeId = 1 AND isAvailable.state = 1
          ) OR (
          ReportTypeId = 2 AND isAvailable.state = 0
          )


          You can add multiple checks using the JOIN:



          SELECT ReferenceData.* 
          FROM ReferenceData JOIN (
          SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
          ) avail1 JOIN (
          SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 2 AND ReportId = 79) AS state
          ) avail2 JOIN (
          SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 3 AND ReportId = 79) AS state
          ) avail3
          WHERE (
          ReportTypeId = 1 AND avail1.state = 1
          ) OR (
          ReportTypeId = 2 AND avail1.state = 0 AND avail2.state = 1
          ) OR (
          ReportTypeId = 3 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 1
          ) OR (
          ReportTypeId = 4 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 0
          )



          demo on dbfiddle.uk







          share|improve this answer
































            1














            You seem to want:



            SELECT refd.* 
            FROM ReferenceData refd
            WHERE (refd.ReportType = 1 AND
            EXISTS (SELECT 1
            FROM ReportData repd
            WHERE repd.ReportId IN (1, 79)
            )
            ) OR
            (refd.ReportType = 2 AND
            EXISTS (SELECT 1
            FROM ReportData repd
            WHERE repd.ReportId NOT IN (1, 79)
            )
            )





            share|improve this answer

























            • This seems like it is a clean solution, but I am not sure why AND is used. I want to select the report if ReportTypeId = 1 else, I want ReportType = 2, but I don't want both Report Types. I am also not sure why we are looking for repd.ReportId IN (1, 79) and not just repd.ReportId = 79.

              – Mwspencer
              Mar 11 at 15:40











            • @Mwspencer . . . Thank you. That was a typo.

              – Gordon Linoff
              Mar 11 at 15:42











            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%2f55069578%2fwhere-statement-hierarchy-for-selecting-rows%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            If RecordTypeId can be ordered**, then you can use the following



            SELECT PerformanceReport 
            FROM ReferenceData
            WHERE ReportTypeId = (
            SELECT MIN(ReportTypeId)
            FROM ReportData
            WHERE ReportTypeId IN (1, 2)
            AND ReportId = 79
            )


            ** by ordered, I mean that the MIN aggregate function will return the expected result. For integers this makes sense, however, if your report type ids are text uuids, then MIN would still work but won't give you the expected result, because it will return the minimum id in lexical order.






            share|improve this answer




















            • 1





              This works great for my case, but I can see that if ReportTypeId = 2 becomes the priority over 1, but not as import as say 3 (2 > 1 > 3), then I'm guessing I'm out of luck?... Well I guess I can create a temp table that would assign a rank of importance, so actually yes I really like this solution, thanks!

              – Mwspencer
              Mar 8 at 19:30












            • @Mwspencer . . . I am baffled at how this answer can be accepted when it does not even seem to be selecting from the correct table.

              – Gordon Linoff
              Mar 8 at 19:46











            • @GordonLinoff, thanks for catching that error!

              – Haleemur Ali
              Mar 8 at 21:32











            • @GordonLinoff, I think it's the idea more than the hard code that I am accepting. As my actual user case is a bit more complicated than my question, and this answer helped created the most straightforward solution. I will admit I have not tested for performance though as that is not important to my specific case. All answers gave the correct output, but this one took the least amount of code.

              – Mwspencer
              Mar 11 at 15:11















            1














            If RecordTypeId can be ordered**, then you can use the following



            SELECT PerformanceReport 
            FROM ReferenceData
            WHERE ReportTypeId = (
            SELECT MIN(ReportTypeId)
            FROM ReportData
            WHERE ReportTypeId IN (1, 2)
            AND ReportId = 79
            )


            ** by ordered, I mean that the MIN aggregate function will return the expected result. For integers this makes sense, however, if your report type ids are text uuids, then MIN would still work but won't give you the expected result, because it will return the minimum id in lexical order.






            share|improve this answer




















            • 1





              This works great for my case, but I can see that if ReportTypeId = 2 becomes the priority over 1, but not as import as say 3 (2 > 1 > 3), then I'm guessing I'm out of luck?... Well I guess I can create a temp table that would assign a rank of importance, so actually yes I really like this solution, thanks!

              – Mwspencer
              Mar 8 at 19:30












            • @Mwspencer . . . I am baffled at how this answer can be accepted when it does not even seem to be selecting from the correct table.

              – Gordon Linoff
              Mar 8 at 19:46











            • @GordonLinoff, thanks for catching that error!

              – Haleemur Ali
              Mar 8 at 21:32











            • @GordonLinoff, I think it's the idea more than the hard code that I am accepting. As my actual user case is a bit more complicated than my question, and this answer helped created the most straightforward solution. I will admit I have not tested for performance though as that is not important to my specific case. All answers gave the correct output, but this one took the least amount of code.

              – Mwspencer
              Mar 11 at 15:11













            1












            1








            1







            If RecordTypeId can be ordered**, then you can use the following



            SELECT PerformanceReport 
            FROM ReferenceData
            WHERE ReportTypeId = (
            SELECT MIN(ReportTypeId)
            FROM ReportData
            WHERE ReportTypeId IN (1, 2)
            AND ReportId = 79
            )


            ** by ordered, I mean that the MIN aggregate function will return the expected result. For integers this makes sense, however, if your report type ids are text uuids, then MIN would still work but won't give you the expected result, because it will return the minimum id in lexical order.






            share|improve this answer















            If RecordTypeId can be ordered**, then you can use the following



            SELECT PerformanceReport 
            FROM ReferenceData
            WHERE ReportTypeId = (
            SELECT MIN(ReportTypeId)
            FROM ReportData
            WHERE ReportTypeId IN (1, 2)
            AND ReportId = 79
            )


            ** by ordered, I mean that the MIN aggregate function will return the expected result. For integers this makes sense, however, if your report type ids are text uuids, then MIN would still work but won't give you the expected result, because it will return the minimum id in lexical order.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 21:33

























            answered Mar 8 at 19:20









            Haleemur AliHaleemur Ali

            12.7k21741




            12.7k21741







            • 1





              This works great for my case, but I can see that if ReportTypeId = 2 becomes the priority over 1, but not as import as say 3 (2 > 1 > 3), then I'm guessing I'm out of luck?... Well I guess I can create a temp table that would assign a rank of importance, so actually yes I really like this solution, thanks!

              – Mwspencer
              Mar 8 at 19:30












            • @Mwspencer . . . I am baffled at how this answer can be accepted when it does not even seem to be selecting from the correct table.

              – Gordon Linoff
              Mar 8 at 19:46











            • @GordonLinoff, thanks for catching that error!

              – Haleemur Ali
              Mar 8 at 21:32











            • @GordonLinoff, I think it's the idea more than the hard code that I am accepting. As my actual user case is a bit more complicated than my question, and this answer helped created the most straightforward solution. I will admit I have not tested for performance though as that is not important to my specific case. All answers gave the correct output, but this one took the least amount of code.

              – Mwspencer
              Mar 11 at 15:11












            • 1





              This works great for my case, but I can see that if ReportTypeId = 2 becomes the priority over 1, but not as import as say 3 (2 > 1 > 3), then I'm guessing I'm out of luck?... Well I guess I can create a temp table that would assign a rank of importance, so actually yes I really like this solution, thanks!

              – Mwspencer
              Mar 8 at 19:30












            • @Mwspencer . . . I am baffled at how this answer can be accepted when it does not even seem to be selecting from the correct table.

              – Gordon Linoff
              Mar 8 at 19:46











            • @GordonLinoff, thanks for catching that error!

              – Haleemur Ali
              Mar 8 at 21:32











            • @GordonLinoff, I think it's the idea more than the hard code that I am accepting. As my actual user case is a bit more complicated than my question, and this answer helped created the most straightforward solution. I will admit I have not tested for performance though as that is not important to my specific case. All answers gave the correct output, but this one took the least amount of code.

              – Mwspencer
              Mar 11 at 15:11







            1




            1





            This works great for my case, but I can see that if ReportTypeId = 2 becomes the priority over 1, but not as import as say 3 (2 > 1 > 3), then I'm guessing I'm out of luck?... Well I guess I can create a temp table that would assign a rank of importance, so actually yes I really like this solution, thanks!

            – Mwspencer
            Mar 8 at 19:30






            This works great for my case, but I can see that if ReportTypeId = 2 becomes the priority over 1, but not as import as say 3 (2 > 1 > 3), then I'm guessing I'm out of luck?... Well I guess I can create a temp table that would assign a rank of importance, so actually yes I really like this solution, thanks!

            – Mwspencer
            Mar 8 at 19:30














            @Mwspencer . . . I am baffled at how this answer can be accepted when it does not even seem to be selecting from the correct table.

            – Gordon Linoff
            Mar 8 at 19:46





            @Mwspencer . . . I am baffled at how this answer can be accepted when it does not even seem to be selecting from the correct table.

            – Gordon Linoff
            Mar 8 at 19:46













            @GordonLinoff, thanks for catching that error!

            – Haleemur Ali
            Mar 8 at 21:32





            @GordonLinoff, thanks for catching that error!

            – Haleemur Ali
            Mar 8 at 21:32













            @GordonLinoff, I think it's the idea more than the hard code that I am accepting. As my actual user case is a bit more complicated than my question, and this answer helped created the most straightforward solution. I will admit I have not tested for performance though as that is not important to my specific case. All answers gave the correct output, but this one took the least amount of code.

            – Mwspencer
            Mar 11 at 15:11





            @GordonLinoff, I think it's the idea more than the hard code that I am accepting. As my actual user case is a bit more complicated than my question, and this answer helped created the most straightforward solution. I will admit I have not tested for performance though as that is not important to my specific case. All answers gave the correct output, but this one took the least amount of code.

            – Mwspencer
            Mar 11 at 15:11













            1














            You can use the following solution:



            SELECT * 
            FROM ReferenceData
            WHERE (
            ReportTypeId = 1
            AND EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
            ) OR (
            ReportTypeId = 2
            AND NOT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
            )


            You can optimize this with a JOIN:



            SELECT ReferenceData.* 
            FROM ReferenceData JOIN (
            SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
            ) isAvailable
            WHERE (
            ReportTypeId = 1 AND isAvailable.state = 1
            ) OR (
            ReportTypeId = 2 AND isAvailable.state = 0
            )


            You can add multiple checks using the JOIN:



            SELECT ReferenceData.* 
            FROM ReferenceData JOIN (
            SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
            ) avail1 JOIN (
            SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 2 AND ReportId = 79) AS state
            ) avail2 JOIN (
            SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 3 AND ReportId = 79) AS state
            ) avail3
            WHERE (
            ReportTypeId = 1 AND avail1.state = 1
            ) OR (
            ReportTypeId = 2 AND avail1.state = 0 AND avail2.state = 1
            ) OR (
            ReportTypeId = 3 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 1
            ) OR (
            ReportTypeId = 4 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 0
            )



            demo on dbfiddle.uk







            share|improve this answer





























              1














              You can use the following solution:



              SELECT * 
              FROM ReferenceData
              WHERE (
              ReportTypeId = 1
              AND EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
              ) OR (
              ReportTypeId = 2
              AND NOT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
              )


              You can optimize this with a JOIN:



              SELECT ReferenceData.* 
              FROM ReferenceData JOIN (
              SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
              ) isAvailable
              WHERE (
              ReportTypeId = 1 AND isAvailable.state = 1
              ) OR (
              ReportTypeId = 2 AND isAvailable.state = 0
              )


              You can add multiple checks using the JOIN:



              SELECT ReferenceData.* 
              FROM ReferenceData JOIN (
              SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
              ) avail1 JOIN (
              SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 2 AND ReportId = 79) AS state
              ) avail2 JOIN (
              SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 3 AND ReportId = 79) AS state
              ) avail3
              WHERE (
              ReportTypeId = 1 AND avail1.state = 1
              ) OR (
              ReportTypeId = 2 AND avail1.state = 0 AND avail2.state = 1
              ) OR (
              ReportTypeId = 3 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 1
              ) OR (
              ReportTypeId = 4 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 0
              )



              demo on dbfiddle.uk







              share|improve this answer



























                1












                1








                1







                You can use the following solution:



                SELECT * 
                FROM ReferenceData
                WHERE (
                ReportTypeId = 1
                AND EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
                ) OR (
                ReportTypeId = 2
                AND NOT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
                )


                You can optimize this with a JOIN:



                SELECT ReferenceData.* 
                FROM ReferenceData JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
                ) isAvailable
                WHERE (
                ReportTypeId = 1 AND isAvailable.state = 1
                ) OR (
                ReportTypeId = 2 AND isAvailable.state = 0
                )


                You can add multiple checks using the JOIN:



                SELECT ReferenceData.* 
                FROM ReferenceData JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
                ) avail1 JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 2 AND ReportId = 79) AS state
                ) avail2 JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 3 AND ReportId = 79) AS state
                ) avail3
                WHERE (
                ReportTypeId = 1 AND avail1.state = 1
                ) OR (
                ReportTypeId = 2 AND avail1.state = 0 AND avail2.state = 1
                ) OR (
                ReportTypeId = 3 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 1
                ) OR (
                ReportTypeId = 4 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 0
                )



                demo on dbfiddle.uk







                share|improve this answer















                You can use the following solution:



                SELECT * 
                FROM ReferenceData
                WHERE (
                ReportTypeId = 1
                AND EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
                ) OR (
                ReportTypeId = 2
                AND NOT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79)
                )


                You can optimize this with a JOIN:



                SELECT ReferenceData.* 
                FROM ReferenceData JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
                ) isAvailable
                WHERE (
                ReportTypeId = 1 AND isAvailable.state = 1
                ) OR (
                ReportTypeId = 2 AND isAvailable.state = 0
                )


                You can add multiple checks using the JOIN:



                SELECT ReferenceData.* 
                FROM ReferenceData JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 1 AND ReportId = 79) AS state
                ) avail1 JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 2 AND ReportId = 79) AS state
                ) avail2 JOIN (
                SELECT EXISTS (SELECT * FROM ReportData WHERE ReportTypeId = 3 AND ReportId = 79) AS state
                ) avail3
                WHERE (
                ReportTypeId = 1 AND avail1.state = 1
                ) OR (
                ReportTypeId = 2 AND avail1.state = 0 AND avail2.state = 1
                ) OR (
                ReportTypeId = 3 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 1
                ) OR (
                ReportTypeId = 4 AND avail1.state = 0 AND avail2.state = 0 AND avail3.state = 0
                )



                demo on dbfiddle.uk








                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 8 at 19:51

























                answered Mar 8 at 19:19









                Sebastian BroschSebastian Brosch

                25.6k124255




                25.6k124255





















                    1














                    You seem to want:



                    SELECT refd.* 
                    FROM ReferenceData refd
                    WHERE (refd.ReportType = 1 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId IN (1, 79)
                    )
                    ) OR
                    (refd.ReportType = 2 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId NOT IN (1, 79)
                    )
                    )





                    share|improve this answer

























                    • This seems like it is a clean solution, but I am not sure why AND is used. I want to select the report if ReportTypeId = 1 else, I want ReportType = 2, but I don't want both Report Types. I am also not sure why we are looking for repd.ReportId IN (1, 79) and not just repd.ReportId = 79.

                      – Mwspencer
                      Mar 11 at 15:40











                    • @Mwspencer . . . Thank you. That was a typo.

                      – Gordon Linoff
                      Mar 11 at 15:42















                    1














                    You seem to want:



                    SELECT refd.* 
                    FROM ReferenceData refd
                    WHERE (refd.ReportType = 1 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId IN (1, 79)
                    )
                    ) OR
                    (refd.ReportType = 2 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId NOT IN (1, 79)
                    )
                    )





                    share|improve this answer

























                    • This seems like it is a clean solution, but I am not sure why AND is used. I want to select the report if ReportTypeId = 1 else, I want ReportType = 2, but I don't want both Report Types. I am also not sure why we are looking for repd.ReportId IN (1, 79) and not just repd.ReportId = 79.

                      – Mwspencer
                      Mar 11 at 15:40











                    • @Mwspencer . . . Thank you. That was a typo.

                      – Gordon Linoff
                      Mar 11 at 15:42













                    1












                    1








                    1







                    You seem to want:



                    SELECT refd.* 
                    FROM ReferenceData refd
                    WHERE (refd.ReportType = 1 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId IN (1, 79)
                    )
                    ) OR
                    (refd.ReportType = 2 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId NOT IN (1, 79)
                    )
                    )





                    share|improve this answer















                    You seem to want:



                    SELECT refd.* 
                    FROM ReferenceData refd
                    WHERE (refd.ReportType = 1 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId IN (1, 79)
                    )
                    ) OR
                    (refd.ReportType = 2 AND
                    EXISTS (SELECT 1
                    FROM ReportData repd
                    WHERE repd.ReportId NOT IN (1, 79)
                    )
                    )






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 11 at 15:42

























                    answered Mar 8 at 19:46









                    Gordon LinoffGordon Linoff

                    792k36316419




                    792k36316419












                    • This seems like it is a clean solution, but I am not sure why AND is used. I want to select the report if ReportTypeId = 1 else, I want ReportType = 2, but I don't want both Report Types. I am also not sure why we are looking for repd.ReportId IN (1, 79) and not just repd.ReportId = 79.

                      – Mwspencer
                      Mar 11 at 15:40











                    • @Mwspencer . . . Thank you. That was a typo.

                      – Gordon Linoff
                      Mar 11 at 15:42

















                    • This seems like it is a clean solution, but I am not sure why AND is used. I want to select the report if ReportTypeId = 1 else, I want ReportType = 2, but I don't want both Report Types. I am also not sure why we are looking for repd.ReportId IN (1, 79) and not just repd.ReportId = 79.

                      – Mwspencer
                      Mar 11 at 15:40











                    • @Mwspencer . . . Thank you. That was a typo.

                      – Gordon Linoff
                      Mar 11 at 15:42
















                    This seems like it is a clean solution, but I am not sure why AND is used. I want to select the report if ReportTypeId = 1 else, I want ReportType = 2, but I don't want both Report Types. I am also not sure why we are looking for repd.ReportId IN (1, 79) and not just repd.ReportId = 79.

                    – Mwspencer
                    Mar 11 at 15:40





                    This seems like it is a clean solution, but I am not sure why AND is used. I want to select the report if ReportTypeId = 1 else, I want ReportType = 2, but I don't want both Report Types. I am also not sure why we are looking for repd.ReportId IN (1, 79) and not just repd.ReportId = 79.

                    – Mwspencer
                    Mar 11 at 15:40













                    @Mwspencer . . . Thank you. That was a typo.

                    – Gordon Linoff
                    Mar 11 at 15:42





                    @Mwspencer . . . Thank you. That was a typo.

                    – Gordon Linoff
                    Mar 11 at 15:42

















                    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%2f55069578%2fwhere-statement-hierarchy-for-selecting-rows%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

                    How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                    List of MPs elected to the English parliament in 1640 (April) Contents List of constituencies and members See also Notes References Navigation menueNational Archives – The Glynde Place ArchivesCobbett's Parliamentary history of England, from the Norman Conquest in 1066 to the year 1803'Aldermen in Parliament', The Aldermen of the City of London: Temp. Henry III – 1912onepage&q&f&#61, false 229