IC Improve Code Recipes

Recipe 2.2 · Python

Paging with OFFSET and FETCH

This recipe has no Python listing. The explanation and any SQL below apply to both languages; switch to C# for the .NET code.

Problem

A grid shows 25 customers per page out of 400,000. The application either loads all of them and pages in memory, or uses a paging query from the SQL Server 2005 days that is long, hard to read and easy to get wrong.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

SQL
-- Not to copy: ROW_NUMBER paging, the 2005-era way.
WITH Numbered AS
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY Name) AS RowNum
    FROM Customer
    WHERE IsActive = 1
)
SELECT *
FROM Numbered
WHERE RowNum BETWEEN (@Page - 1) * @Size + 1 AND @Page * @Size

This works, and it appears in about 692 files across 10 engagements in my archive. But SELECT * drags every column through the plan, and ordering by Name alone is not deterministic: two customers with the same name can swap places between pages, so one appears twice and another never appears.

The improved recipe

SQL
CREATE OR ALTER PROCEDURE dbo.Customer_Page
    @PageNumber INT = 1,
    @PageSize   INT = 25
AS
BEGIN
    SET NOCOUNT ON;

    IF @PageNumber IS NULL OR @PageNumber < 1
        SET @PageNumber = 1;
    IF @PageSize IS NULL OR @PageSize NOT BETWEEN 1 AND 200
        SET @PageSize = 25;

    SELECT c.CustomerId,
           c.Name,
           c.City,
           c.CreatedUtc,
           COUNT(*) OVER () AS TotalRows
    FROM   dbo.Customer AS c
    WHERE  c.IsActive = 1
    ORDER BY c.Name, c.CustomerId
    OFFSET (@PageNumber - 1) * @PageSize ROWS
    FETCH NEXT @PageSize ROWS ONLY;
END;

For exports, feeds and anything a person does not click through page by page, use keyset paging instead:

SQL
CREATE OR ALTER PROCEDURE dbo.AuditLog_NextPage
    @AfterAuditId BIGINT = 0,
    @PageSize     INT    = 1000
AS
BEGIN
    SET NOCOUNT ON;

    SELECT TOP (@PageSize)
           a.AuditId, a.ChangedUtc, a.Description
    FROM   dbo.AuditLog AS a
    WHERE  a.AuditId > @AfterAuditId
    ORDER BY a.AuditId;
END;

How it works

OFFSET ... FETCH (SQL Server 2012 and later) is part of the ORDER BY clause. It skips a number of rows and returns the next batch. The procedure clamps the inputs, so a caller cannot request page 0 or ask for a million rows per page.

The ORDER BY ends with the primary key. That tie-breaker makes the order deterministic, which is the only way paging can be correct. COUNT(*) OVER () returns the total number of matching rows on every row, so the grid can show "page 3 of 120" without a second query.

Keyset paging remembers where the last page ended instead of counting rows to skip. The caller passes the last AuditId it saw and gets the next batch. With an index on the key, every page costs the same, whether it is the first or the ten-thousandth. Offset paging, by contrast, must read and throw away all the skipped rows, so page 10,000 is far slower than page 1.

Variations and pitfalls

  • Index the sort. An index on (IsActive, Name, CustomerId) that includes City and CreatedUtc lets SQL Server read just the rows it needs. Without one, every page sorts the whole table.
  • COUNT(*) OVER () is not free. It forces SQL Server to find every matching row, not just the 25 it returns. On large tables run a separate count query, cache it briefly (Chapter 3), or show "more results" instead of an exact page count.
  • Keyset paging on non-unique columns. If you page by date, pass both the last date and the last ID, and filter with WHERE (ChangedUtc > @LastUtc) OR (ChangedUtc = @LastUtc AND AuditId > @LastId).
  • Filtering. Combine this recipe with the dynamic search in Recipe 2.5 when the grid has optional filters.
  • Chapter 16 shows the C# side: a paging helper for grids that calls this kind of procedure.