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.
- Categoría
- Ventana
- Returns
page of rows- In this category
- 39 of 79
Sintaxis
ROW_NUMBER() OVER (ORDER BY id) | WHERE rn BETWEEN 101 AND 120
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | MySQL 8.0+ |
| SQLite | Sí | SQLite 3.25+ |
| Oracle | Sí | Supported under this name. |
Ejemplos
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;
Conviene saberlo
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.