Wednesday, November 2, 2016

ROW_NUMBER in T-SQL is another thing I keep botching in interviews. (twice now)

The interview challenge: How do you return a page of "pagination" more than one page deep in T-SQL results? Well, if it's just the first page, that's easy right? You do something like what follows, to use the Problems table I made here as an example.

SELECT TOP(10) * FROM Problems
WHERE PersonId != 4
ORDER BY ProblemId

 
 

But if we want a different "page" ...then what. I had this in my notes, but I suspected it was really expensive (and I still think that) and as a result I found this online which offered:

SELECT * FROM
(
   SELECT ROW_NUMBER() OVER ( ORDER BY ProblemId ) AS Spot,
         * FROM Problems
   WHERE PersonId != 4
) AS WhateverYoudLikeHere
WHERE Spot >= 11 AND Spot <= 20
ORDER BY ProblemId

No comments:

Post a Comment