Skip to content

Instantly share code, notes, and snippets.

@konstantindenerz
Created March 24, 2015 13:54
Show Gist options
  • Save konstantindenerz/eca5ca453e23f8e5772b to your computer and use it in GitHub Desktop.
Save konstantindenerz/eca5ca453e23f8e5772b to your computer and use it in GitHub Desktop.
Pagination, Filtering, Sorting with Total Row Count // SQL Server
DECLARE @PageNumber AS INT, @RowsPerPage AS INT
SET @PageNumber = 1
SET @RowsPerPage = 20
SELECT * FROM (
SELECT ROW_NUMBER() OVER(ORDER BY Id /* Sort example*/) AS [Meta.Index], COUNT(Id) OVER() [Meta.Total],
i.* FROM Items i
WHERE Id > 5 AND Id < 20 -- Filter example
) AS result
WHERE [Meta.Index] BETWEEN ((@PageNumber - 1) * @RowsPerPage + 1) AND (@PageNumber * @RowsPerPage) -- Pagination
ORDER BY [Meta.Index]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment