MSSQL - Query efficiency to many filters












1














I'm making an ASP.NET website which users can select more than 20 different filters at the same time. Something like 'Product Type', 'Year', 'State-of-Usage', 'Color', 'Size' and so forth.



Many of these items are related to other tables. So, my query makes a 'SELECT' using WHERE and 'INNER JOIN' to 12 other tables.



The problem resides in parameters that can be present or not.
I mean, depending of the user choice, some parameters will be NULL or not and I can't utilize them in my query (like using ISNULL()) because I'm affraid of return a wrong result caused by this.



So, my solution is build the query string depending of the parameters received , I mean, the query will consider only those which have real values.



declare @SEARCH_QUERY nvarchar(max);

set @SEARCH_QUERY = 'select AcervoID, Categoria, Fabricante, Personagem, Estado,
IIF(LEN(Description) > 120, LEFT(Description,120) + ''...'', Description) [mDescription],
Value, Availability, ActiveLink, Title,
RIGHT([thumb], CHARINDEX('''', REVERSE([thumb])) -1) [Image],
E.UsoID, E.FontAwesome
from Acervo A
inner join Categorias C on C.CatID = A.Categoria
inner join Fabricantes F on F.FabID = A.Fabricante
inner join Personagem P on P.PersID = A.Personagem
inner join EstadoUso E on E.UsoID = A.Estado
where A.Ativo = ''true'' and A.Disponiveis > 0'



if @m_Cat >-1
set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Categoria = ' + convert(nvarchar(4),@m_Cat)
if @m_Fab >-1
set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.fabricante = ' + convert(nvarchar(4),@m_Fab)
if @m_Pers > -1
set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Personagem = ' + convert(nvarchar(4),@m_Pers)
if @m_EU is not null
set @SEARCH_QUERY = @SEARCH_QUERY + @m_EU



exec sp_executeSQL @SEARCH_QUERY


Is there a best way to do it?



Thanks in advance.










share|improve this question





























    1














    I'm making an ASP.NET website which users can select more than 20 different filters at the same time. Something like 'Product Type', 'Year', 'State-of-Usage', 'Color', 'Size' and so forth.



    Many of these items are related to other tables. So, my query makes a 'SELECT' using WHERE and 'INNER JOIN' to 12 other tables.



    The problem resides in parameters that can be present or not.
    I mean, depending of the user choice, some parameters will be NULL or not and I can't utilize them in my query (like using ISNULL()) because I'm affraid of return a wrong result caused by this.



    So, my solution is build the query string depending of the parameters received , I mean, the query will consider only those which have real values.



    declare @SEARCH_QUERY nvarchar(max);

    set @SEARCH_QUERY = 'select AcervoID, Categoria, Fabricante, Personagem, Estado,
    IIF(LEN(Description) > 120, LEFT(Description,120) + ''...'', Description) [mDescription],
    Value, Availability, ActiveLink, Title,
    RIGHT([thumb], CHARINDEX('''', REVERSE([thumb])) -1) [Image],
    E.UsoID, E.FontAwesome
    from Acervo A
    inner join Categorias C on C.CatID = A.Categoria
    inner join Fabricantes F on F.FabID = A.Fabricante
    inner join Personagem P on P.PersID = A.Personagem
    inner join EstadoUso E on E.UsoID = A.Estado
    where A.Ativo = ''true'' and A.Disponiveis > 0'



    if @m_Cat >-1
    set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Categoria = ' + convert(nvarchar(4),@m_Cat)
    if @m_Fab >-1
    set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.fabricante = ' + convert(nvarchar(4),@m_Fab)
    if @m_Pers > -1
    set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Personagem = ' + convert(nvarchar(4),@m_Pers)
    if @m_EU is not null
    set @SEARCH_QUERY = @SEARCH_QUERY + @m_EU



    exec sp_executeSQL @SEARCH_QUERY


    Is there a best way to do it?



    Thanks in advance.










    share|improve this question



























      1












      1








      1







      I'm making an ASP.NET website which users can select more than 20 different filters at the same time. Something like 'Product Type', 'Year', 'State-of-Usage', 'Color', 'Size' and so forth.



      Many of these items are related to other tables. So, my query makes a 'SELECT' using WHERE and 'INNER JOIN' to 12 other tables.



      The problem resides in parameters that can be present or not.
      I mean, depending of the user choice, some parameters will be NULL or not and I can't utilize them in my query (like using ISNULL()) because I'm affraid of return a wrong result caused by this.



      So, my solution is build the query string depending of the parameters received , I mean, the query will consider only those which have real values.



      declare @SEARCH_QUERY nvarchar(max);

      set @SEARCH_QUERY = 'select AcervoID, Categoria, Fabricante, Personagem, Estado,
      IIF(LEN(Description) > 120, LEFT(Description,120) + ''...'', Description) [mDescription],
      Value, Availability, ActiveLink, Title,
      RIGHT([thumb], CHARINDEX('''', REVERSE([thumb])) -1) [Image],
      E.UsoID, E.FontAwesome
      from Acervo A
      inner join Categorias C on C.CatID = A.Categoria
      inner join Fabricantes F on F.FabID = A.Fabricante
      inner join Personagem P on P.PersID = A.Personagem
      inner join EstadoUso E on E.UsoID = A.Estado
      where A.Ativo = ''true'' and A.Disponiveis > 0'



      if @m_Cat >-1
      set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Categoria = ' + convert(nvarchar(4),@m_Cat)
      if @m_Fab >-1
      set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.fabricante = ' + convert(nvarchar(4),@m_Fab)
      if @m_Pers > -1
      set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Personagem = ' + convert(nvarchar(4),@m_Pers)
      if @m_EU is not null
      set @SEARCH_QUERY = @SEARCH_QUERY + @m_EU



      exec sp_executeSQL @SEARCH_QUERY


      Is there a best way to do it?



      Thanks in advance.










      share|improve this question















      I'm making an ASP.NET website which users can select more than 20 different filters at the same time. Something like 'Product Type', 'Year', 'State-of-Usage', 'Color', 'Size' and so forth.



      Many of these items are related to other tables. So, my query makes a 'SELECT' using WHERE and 'INNER JOIN' to 12 other tables.



      The problem resides in parameters that can be present or not.
      I mean, depending of the user choice, some parameters will be NULL or not and I can't utilize them in my query (like using ISNULL()) because I'm affraid of return a wrong result caused by this.



      So, my solution is build the query string depending of the parameters received , I mean, the query will consider only those which have real values.



      declare @SEARCH_QUERY nvarchar(max);

      set @SEARCH_QUERY = 'select AcervoID, Categoria, Fabricante, Personagem, Estado,
      IIF(LEN(Description) > 120, LEFT(Description,120) + ''...'', Description) [mDescription],
      Value, Availability, ActiveLink, Title,
      RIGHT([thumb], CHARINDEX('''', REVERSE([thumb])) -1) [Image],
      E.UsoID, E.FontAwesome
      from Acervo A
      inner join Categorias C on C.CatID = A.Categoria
      inner join Fabricantes F on F.FabID = A.Fabricante
      inner join Personagem P on P.PersID = A.Personagem
      inner join EstadoUso E on E.UsoID = A.Estado
      where A.Ativo = ''true'' and A.Disponiveis > 0'



      if @m_Cat >-1
      set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Categoria = ' + convert(nvarchar(4),@m_Cat)
      if @m_Fab >-1
      set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.fabricante = ' + convert(nvarchar(4),@m_Fab)
      if @m_Pers > -1
      set @SEARCH_QUERY = @SEARCH_QUERY + ' and A.Personagem = ' + convert(nvarchar(4),@m_Pers)
      if @m_EU is not null
      set @SEARCH_QUERY = @SEARCH_QUERY + @m_EU



      exec sp_executeSQL @SEARCH_QUERY


      Is there a best way to do it?



      Thanks in advance.







      sql-server-2012 ado.net






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 29 '18 at 15:27

























      asked Dec 29 '18 at 15:20









      David BS

      1083




      1083






















          1 Answer
          1






          active

          oldest

          votes


















          3














          The basic form you have is correct, though you want to avoid concatenating parameters into the string the way you have. See:




          • Revisiting catch-all queries


          • #BackToBasics : An Updated "Kitchen Sink" Example



          The efficiency part will depend ultimately on the supporting indexes you have for your queries, along with other local factors, like hardware, blocking, rows returned, etc.






          share|improve this answer





















          • Thank you. I will see the docs. I'm avoinding the usage of indexes because I'm not sure if they can really help or disturb the "inner join" operations. The main table has almost 120 fields and, at least, 60 of them are related to other tables. So, I'm a little bit worried with so many indexes to be created (and kept by MS-SQL engine) in an online system.
            – David BS
            Dec 29 '18 at 17:19






          • 3




            @DavidBS If your tables are that wide, take a look at this post: Do You Have Tables In Your Tables?. It might be time to normalize a bit.
            – Erik Darling
            Dec 29 '18 at 17:49






          • 2




            As a rule, indices on join columns will be extremely beneficial to query performance. its also not clear what problem you are trying to solve - your title suggests performance, your question suggests correctness. You might also consider using an ORM that will write queries for you.. e.g. github.com/ServiceStack/ServiceStack.OrmLite
            – kevinc
            Dec 29 '18 at 21:10










          • @kevinc, my goal it to get performance and, as shown by Erik above, the code can be better if following some code standards to do it. Anyway, thank you for recommendation - I'll see it tomorrow.
            – David BS
            Dec 29 '18 at 21:58











          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
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f225980%2fmssql-query-efficiency-to-many-filters%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









          3














          The basic form you have is correct, though you want to avoid concatenating parameters into the string the way you have. See:




          • Revisiting catch-all queries


          • #BackToBasics : An Updated "Kitchen Sink" Example



          The efficiency part will depend ultimately on the supporting indexes you have for your queries, along with other local factors, like hardware, blocking, rows returned, etc.






          share|improve this answer





















          • Thank you. I will see the docs. I'm avoinding the usage of indexes because I'm not sure if they can really help or disturb the "inner join" operations. The main table has almost 120 fields and, at least, 60 of them are related to other tables. So, I'm a little bit worried with so many indexes to be created (and kept by MS-SQL engine) in an online system.
            – David BS
            Dec 29 '18 at 17:19






          • 3




            @DavidBS If your tables are that wide, take a look at this post: Do You Have Tables In Your Tables?. It might be time to normalize a bit.
            – Erik Darling
            Dec 29 '18 at 17:49






          • 2




            As a rule, indices on join columns will be extremely beneficial to query performance. its also not clear what problem you are trying to solve - your title suggests performance, your question suggests correctness. You might also consider using an ORM that will write queries for you.. e.g. github.com/ServiceStack/ServiceStack.OrmLite
            – kevinc
            Dec 29 '18 at 21:10










          • @kevinc, my goal it to get performance and, as shown by Erik above, the code can be better if following some code standards to do it. Anyway, thank you for recommendation - I'll see it tomorrow.
            – David BS
            Dec 29 '18 at 21:58
















          3














          The basic form you have is correct, though you want to avoid concatenating parameters into the string the way you have. See:




          • Revisiting catch-all queries


          • #BackToBasics : An Updated "Kitchen Sink" Example



          The efficiency part will depend ultimately on the supporting indexes you have for your queries, along with other local factors, like hardware, blocking, rows returned, etc.






          share|improve this answer





















          • Thank you. I will see the docs. I'm avoinding the usage of indexes because I'm not sure if they can really help or disturb the "inner join" operations. The main table has almost 120 fields and, at least, 60 of them are related to other tables. So, I'm a little bit worried with so many indexes to be created (and kept by MS-SQL engine) in an online system.
            – David BS
            Dec 29 '18 at 17:19






          • 3




            @DavidBS If your tables are that wide, take a look at this post: Do You Have Tables In Your Tables?. It might be time to normalize a bit.
            – Erik Darling
            Dec 29 '18 at 17:49






          • 2




            As a rule, indices on join columns will be extremely beneficial to query performance. its also not clear what problem you are trying to solve - your title suggests performance, your question suggests correctness. You might also consider using an ORM that will write queries for you.. e.g. github.com/ServiceStack/ServiceStack.OrmLite
            – kevinc
            Dec 29 '18 at 21:10










          • @kevinc, my goal it to get performance and, as shown by Erik above, the code can be better if following some code standards to do it. Anyway, thank you for recommendation - I'll see it tomorrow.
            – David BS
            Dec 29 '18 at 21:58














          3












          3








          3






          The basic form you have is correct, though you want to avoid concatenating parameters into the string the way you have. See:




          • Revisiting catch-all queries


          • #BackToBasics : An Updated "Kitchen Sink" Example



          The efficiency part will depend ultimately on the supporting indexes you have for your queries, along with other local factors, like hardware, blocking, rows returned, etc.






          share|improve this answer












          The basic form you have is correct, though you want to avoid concatenating parameters into the string the way you have. See:




          • Revisiting catch-all queries


          • #BackToBasics : An Updated "Kitchen Sink" Example



          The efficiency part will depend ultimately on the supporting indexes you have for your queries, along with other local factors, like hardware, blocking, rows returned, etc.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 29 '18 at 17:08









          Erik Darling

          21k1263103




          21k1263103












          • Thank you. I will see the docs. I'm avoinding the usage of indexes because I'm not sure if they can really help or disturb the "inner join" operations. The main table has almost 120 fields and, at least, 60 of them are related to other tables. So, I'm a little bit worried with so many indexes to be created (and kept by MS-SQL engine) in an online system.
            – David BS
            Dec 29 '18 at 17:19






          • 3




            @DavidBS If your tables are that wide, take a look at this post: Do You Have Tables In Your Tables?. It might be time to normalize a bit.
            – Erik Darling
            Dec 29 '18 at 17:49






          • 2




            As a rule, indices on join columns will be extremely beneficial to query performance. its also not clear what problem you are trying to solve - your title suggests performance, your question suggests correctness. You might also consider using an ORM that will write queries for you.. e.g. github.com/ServiceStack/ServiceStack.OrmLite
            – kevinc
            Dec 29 '18 at 21:10










          • @kevinc, my goal it to get performance and, as shown by Erik above, the code can be better if following some code standards to do it. Anyway, thank you for recommendation - I'll see it tomorrow.
            – David BS
            Dec 29 '18 at 21:58


















          • Thank you. I will see the docs. I'm avoinding the usage of indexes because I'm not sure if they can really help or disturb the "inner join" operations. The main table has almost 120 fields and, at least, 60 of them are related to other tables. So, I'm a little bit worried with so many indexes to be created (and kept by MS-SQL engine) in an online system.
            – David BS
            Dec 29 '18 at 17:19






          • 3




            @DavidBS If your tables are that wide, take a look at this post: Do You Have Tables In Your Tables?. It might be time to normalize a bit.
            – Erik Darling
            Dec 29 '18 at 17:49






          • 2




            As a rule, indices on join columns will be extremely beneficial to query performance. its also not clear what problem you are trying to solve - your title suggests performance, your question suggests correctness. You might also consider using an ORM that will write queries for you.. e.g. github.com/ServiceStack/ServiceStack.OrmLite
            – kevinc
            Dec 29 '18 at 21:10










          • @kevinc, my goal it to get performance and, as shown by Erik above, the code can be better if following some code standards to do it. Anyway, thank you for recommendation - I'll see it tomorrow.
            – David BS
            Dec 29 '18 at 21:58
















          Thank you. I will see the docs. I'm avoinding the usage of indexes because I'm not sure if they can really help or disturb the "inner join" operations. The main table has almost 120 fields and, at least, 60 of them are related to other tables. So, I'm a little bit worried with so many indexes to be created (and kept by MS-SQL engine) in an online system.
          – David BS
          Dec 29 '18 at 17:19




          Thank you. I will see the docs. I'm avoinding the usage of indexes because I'm not sure if they can really help or disturb the "inner join" operations. The main table has almost 120 fields and, at least, 60 of them are related to other tables. So, I'm a little bit worried with so many indexes to be created (and kept by MS-SQL engine) in an online system.
          – David BS
          Dec 29 '18 at 17:19




          3




          3




          @DavidBS If your tables are that wide, take a look at this post: Do You Have Tables In Your Tables?. It might be time to normalize a bit.
          – Erik Darling
          Dec 29 '18 at 17:49




          @DavidBS If your tables are that wide, take a look at this post: Do You Have Tables In Your Tables?. It might be time to normalize a bit.
          – Erik Darling
          Dec 29 '18 at 17:49




          2




          2




          As a rule, indices on join columns will be extremely beneficial to query performance. its also not clear what problem you are trying to solve - your title suggests performance, your question suggests correctness. You might also consider using an ORM that will write queries for you.. e.g. github.com/ServiceStack/ServiceStack.OrmLite
          – kevinc
          Dec 29 '18 at 21:10




          As a rule, indices on join columns will be extremely beneficial to query performance. its also not clear what problem you are trying to solve - your title suggests performance, your question suggests correctness. You might also consider using an ORM that will write queries for you.. e.g. github.com/ServiceStack/ServiceStack.OrmLite
          – kevinc
          Dec 29 '18 at 21:10












          @kevinc, my goal it to get performance and, as shown by Erik above, the code can be better if following some code standards to do it. Anyway, thank you for recommendation - I'll see it tomorrow.
          – David BS
          Dec 29 '18 at 21:58




          @kevinc, my goal it to get performance and, as shown by Erik above, the code can be better if following some code standards to do it. Anyway, thank you for recommendation - I'll see it tomorrow.
          – David BS
          Dec 29 '18 at 21:58


















          draft saved

          draft discarded




















































          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f225980%2fmssql-query-efficiency-to-many-filters%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

          Human spaceflight

          Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

          張江高科駅