Using OFFSET
for pagination in SQL Server can be inefficient with large datasets. Keyset pagination offers a superior alternative.
Unlike rowset pagination (which scans all preceding rows), keyset pagination uses a unique index to directly access the starting point of a page. This significantly reduces unnecessary data retrieval. A unique index on the pagination key (and any additional query columns) is crucial for optimal performance.
Let's say we have a table named TableName
with an index on Id
, and we need to paginate using the latest Id
value.
Initial Query (First Page):
<code class="language-sql">SELECT TOP (@numRows) * FROM TableName ORDER BY Id DESC;</code>
Subsequent Queries:
<code class="language-sql">SELECT TOP (@numRows) * FROM TableName WHERE Id < @lastId ORDER BY Id DESC;</code>
Where @lastId
is the lowest Id
value from the previous page's results.
For columns lacking unique values, include a secondary column in both the `ORDER BY` and `WHERE` clauses, along with a composite index on both columns.
Important Considerations:
The above is the detailed content of How Can Keyset Pagination Improve SQL Server Pagination Efficiency Over OFFSET?. For more information, please follow other related articles on the PHP Chinese website!