title: How to Optimize the Use of the "OR" Clause When Used with Parameters (SQL Server 2008)
body: <p>I wonder if there is any wise way to rewrite the following query so that the indexes on columns get used by optimizer?</p>
  <pre class="lang-sql prettyprint-override"><code>CREATE PROCEDURE select_Proc1
      @Key1 int=0,
      @Key2 int=0
  AS
  BEGIN
      SELECT key3
      FROM Or_Table
      WHERE (@key1 = 0 OR Key1 = @Key1) AND
            (@key2 = 0 OR Key2 = @Key2)
  END
  GO
  </code></pre>
  <p>According to this article <a href="https://web.archive.org/web/20110101175744/https://www.sql-server-performance.com/articles/per/optimize_or_clause_p1.aspx" rel="noreferrer">How to Optimize the Use of the &quot;OR&quot; Clause When Used with Parameters</a> by Preethiviraj Kulasingham:</p>
  <blockquote>
  <p>Even though columns in the <code>WHERE</code> clauses are covered by indexes, SQL Server is unable to use these indexes. This raises the question as to whether anything is &quot;blocking&quot; the use of the indexes? The answer to this question is yes -- the culprits are the parameters and the <code>OR</code> condition.</p>
  <p>The parameters are not covered by indexes, which means SQL Server cannot use any of the indexes to evaluate <code>@key1=0</code> (a condition which also applies to <code>@key2=0</code>).</p>
  <p>Effectively, this means SQL Server cannot use indexes to evaluate the clause <code>@key1=0 OR Key1= @key1</code> (as the <code>OR</code> clause is the union of rows covered by both conditions). The same principle applies to the other clause (re. key2) as well. This leads SQL Server to conclude that no indexes can be used to extract the rows, leaving SQL Server to utilize the next best approach -- a clustered index scan</p>
  </blockquote>
  <p>As you see, the SQL optimizer will not use indexes on columns if the predicates are <code>OR</code>ed in the <code>WHERE</code> clause. One solution for this problem, is to separate queries with <code>IF</code> clause for all possible combination of parameters.</p>
  <p>Now my question is - What should we do if the possible combinations are more that just three or four? Writing a separate query for each combination does not seem a rational solution.</p>
  <p>Is there any other workaround for this problem?</p>