title: Paging, sorting and filtering in a stored procedure (SQL Server)
body: <p>I was looking at different ways of writing a stored procedure to return a "page" of data. This was for use with the ASP <code>ObjectDataSource</code>, but it could be considered a more general problem.</p>
  
  <p>The requirement is to return a subset of the data based on the usual paging parameters; <code>startPageIndex</code> and <code>maximumRows</code>, but also a <code>sortBy</code> parameter to allow the data to be sorted. Also there are some parameters passed in to filter the data on various conditions.</p>
  
  <p>One common way to do this seems to be something like this:</p>
  
  <p>[Method 1]</p>
  
  <pre class="lang-sql prettyprint-override"><code>;WITH stuff AS (
      SELECT 
          CASE 
              WHEN @SortBy = 'Name' THEN ROW_NUMBER() OVER (ORDER BY Name)
              WHEN @SortBy = 'Name DESC' THEN ROW_NUMBER() OVER (ORDER BY Name DESC)
              WHEN @SortBy = ... 
              ELSE ROW_NUMBER() OVER (ORDER BY whatever)
          END AS Row,
          ., 
          ., 
          .,
      FROM Table1
      INNER JOIN Table2 ...
      LEFT JOIN Table3 ...
      WHERE ... (lots of things to check)
      ) 
  SELECT *
  FROM stuff 
  WHERE (Row &gt; @startRowIndex)
  AND   (Row &lt;= @startRowIndex + @maximumRows OR @maximumRows &lt;= 0)
  ORDER BY Row
  </code></pre>
  
  <p>One problem with this is that it doesn't give the total count and generally we need another stored procedure for that. This second stored procedure has to replicate the parameter list and the complex <code>WHERE</code> clause. Not nice.</p>
  
  <p>One solution is to append an extra column to the final select list, (SELECT COUNT(*) FROM stuff) AS <code>TotalRows</code>. This gives us the total but repeats it for every row in the result set, which is not ideal.</p>
  
  <p>[Method 2]<br>
  An interesting alternative is given here (<a href="https://web.archive.org/web/20211020111700/https://www.4guysfromrolla.com/articles/032206-1.aspx" rel="noreferrer">https://web.archive.org/web/20211020111700/https://www.4guysfromrolla.com/articles/032206-1.aspx</a>) using dynamic SQL. He reckons that the performance is better because the CASE statement in the first solution drags things down. Fair enough, and this solution makes it easy to get the totalRows and slap it into an output parameter. But I hate coding dynamic SQL. All that 'bit of SQL ' + STR(@parm1) +' bit more SQL' gubbins.</p>
  
  <p>[Method 3]<br>
  The only way I can find to get what I want, without repeating code which would have to be synchronized, and keeping things reasonably readable is to go back to the "old way" of using a table variable:</p>
  
  <pre class="lang-sql prettyprint-override"><code>DECLARE @stuff TABLE (Row INT, ...)
  
  INSERT INTO @stuff
  SELECT 
      CASE 
          WHEN @SortBy = 'Name' THEN ROW_NUMBER() OVER (ORDER BY Name)
          WHEN @SortBy = 'Name DESC' THEN ROW_NUMBER() OVER (ORDER BY Name DESC)
          WHEN @SortBy = ... 
          ELSE ROW_NUMBER() OVER (ORDER BY whatever)
      END AS Row,
      ., 
      ., 
      .,
  FROM Table1
  INNER JOIN Table2 ...
  LEFT JOIN Table3 ...
  WHERE ... (lots of things to check)
  
  SELECT *
  FROM stuff 
  WHERE (Row &gt; @startRowIndex)
  AND   (Row &lt;= @startRowIndex + @maximumRows OR @maximumRows &lt;= 0)
  ORDER BY Row
  </code></pre>
  
  <p>(Or a similar method using an IDENTITY column on the table variable).
  Here I can just add a SELECT COUNT on the table variable to get the totalRows and put it into an output parameter.</p>
  
  <p>I did some tests and with a fairly simple version of the query (no sortBy and no filter), method 1 seems to come up on top (almost twice as quick as the other 2). Then I decided to test probably I needed the complexity and I needed the SQL to be in stored procedures. With this I get method 1 taking nearly twice as long as the other 2 methods. Which seems strange.</p>
  
  <p>Is there any good reason why I shouldn't spurn CTEs and stick with method 3?</p>
  
  <hr>
  
  <h2>UPDATE - 15 March 2012</h2>
  
  <p>I tried adapting Method 1 to dump the page from the CTE into a temporary table so that I could extract the TotalRows and then select just the relevant columns for the resultset. This seemed to add significantly to the time (more than I expected). I should add that I'm running this on a laptop with SQL Server Express 2008 (all that I have available) but still the comparison should be valid.</p>
  
  <p>I looked again at the dynamic SQL method. It turns out I wasn't really doing it properly (just concatenating strings together). I set it up as in the documentation for <code>sp_executesql</code> (with a parameter description string and parameter list) and it's much more readable. Also this method runs fastest in my environment. Why that should be still baffles me, but I guess the answer is hinted at in Hogan's comment.</p>