// window reference

SQL pagination with ROW_NUMBER

Number the rows with ROW_NUMBER() OVER (ORDER BY ...) and keep a range of numbers per page; it does the same work as OFFSET but also hands you page totals.

類別
視窗
Returns
page of rows
In this category
39 of 79

語法

ROW_NUMBER() OVER (ORDER BY id) | WHERE rn BETWEEN 101 AND 120

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 MySQL 8.0+
SQLite 是 SQLite 3.25+
Oracle 是 Supported under this name.

範例

Any engine

WITH p AS (
  SELECT pr.*, ROW_NUMBER() OVER (ORDER BY created_at DESC, id) AS rn,
         COUNT(*) OVER () AS total
  FROM products pr
)
SELECT * FROM p WHERE rn BETWEEN 101 AND 120;

小知識

  • The row numbers exist per query execution; there is no stored ordering. Pagination is only stable with a total ORDER BY (unique tiebreaker) between pages.
  • Deep OFFSET pages make the engine read and discard all skipped rows; the numbered range does the same work unless you switch to keyset pagination (WHERE id > last_id).
  • COUNT(*) OVER () in the same query gives the total rows for page counts without a second query.

Questions about Window Pagination

Is ROW_NUMBER pagination better than OFFSET?

For deep pages, mostly cosmetic: both scan up to the page. The real win is keyset pagination (WHERE sort_key > last_value), which is an index seek; use ROW_NUMBER when you need page numbers or totals anyway.

Why do rows repeat or vanish between pages?

The ORDER BY is not total. Tied sort keys can permute between queries, so the same row can land on two pages. Add a unique tiebreaker column to the ORDER BY.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.