I have the following select SQL that does a basic select statement although it does include a calculated column:
Select *
From
(
Select *,
ROW_NUMBER() OVER
(ORDER BY
CASE WHEN @sortBy = 0 THEN R.DateCreated End Desc,
CASE WHEN @sortBy = 1 THEN R.DateCreated end Asc,
CASE WHEN @sortBy = 2 THEN TotalVotes END Desc,
CASE WHEN @sortBy = 2 THEN R.TotalFoundNotUseful END Desc
) AS RowNumber
From
(
Select *, (TotalFoundUseful + TotalFoundNotUseful) As TotalVotes
From Reviews
Where (DealID = @dealID) And (TotalAbuses < 10) And (Deleted = 0)
) As R
) As Rev
Where RowNumber BETWEEN @startRecord AND @endRecord
If you look carefully, the SELECT statement itself is executed 3 times. I can’t believe that this is necessary. Is there a way to reduce this to 2 select statements (or possibly even one). I don’t actually need to return the RowNumber. It is only used for selecting rows within a certain range.
You can do it with two by putting the rownumber in with the original select against reviews. You can’t go to one if you want to have a WHERE clause on a windowing function like ROW_NUMBER.
You do have to write
TotalFoundUseful + TotalFoundNotUsefultwice but it will only be evaluated once so that doesn’t effect performance.I also wouldn’t expect moving to two to have any effect on performance but you should test it.