PostgreSQL Error 2201X: Invalid Row Count in Offset
In this article
Error 2201X means the row count you passed to an OFFSET (or FETCH) clause is invalid — almost always a negative number, a non-integer, or a value that arrived as NULL or an empty string from your application layer. PostgreSQL's SQLSTATE 2201X is defined as "invalid row count in result offset clause," so the fix is to find the offending query and correct the value before it reaches the database. You cannot suppress the error with a cast or a default; you have to fix the input.
What You'll Need
- Access to the PostgreSQL server logs or your application's error log so you can see the failing statement.
- A client such as
psql, pgAdmin, or DBeaver to reproduce the query. - Permission to read the application code or ORM configuration that builds the query.
- The exact text of the query and the bound parameters, if your driver uses placeholders.
Step-by-Step
- Locate the failing statement. Check the PostgreSQL log (commonly in the data directory's
log/folder, or wherever your host writes logs) for the error line. It will read something likeERROR: invalid row count in result offset clausefollowed bySTATEMENT:and the SQL. If the log does not include the statement, enablelog_min_error_statementaterrorlevel and reproduce the problem. Labels and paths vary by version, hosting provider, and region, so look for the logging section rather than an exact menu name. - Read the query and spot the OFFSET. Look for
OFFSETand, if present,FETCH FIRST n ROWS ONLYorLIMIT. Note whether the number is a literal (e.g.OFFSET 20) or a placeholder (e.g.OFFSET $2). Placeholders are where the trouble usually lives. - Reproduce it in a client. Run the query with the same values in
psql. A negative value fails immediately:
Confirm the error text matches what you saw in the log. If it does not reproduce with a literal, the problem is the parameter binding.SELECT * FROM orders ORDER BY id OFFSET -1; -- ERROR: invalid row count in result offset clause - Inspect the bound value. In your application, log the raw value passed for the offset before it is sent. Common culprits: a pagination variable that is
null, an empty string from a query parameter, a string like"abc", or a computed value such aspage - 1that goes negative whenpageis 0. - Validate before the query. Coerce the value to a non-negative integer in application code. For example, parse the string, reject anything that is not a whole number, and clamp negatives to 0. Do this in one shared helper so every paginated endpoint uses the same rule.
- Fix the arithmetic. If your offset is
(page - 1) * pageSize, guard the page number so it starts at 1. A page of 0 produces a negative offset, which is exactly what triggers 2201X. - Cast explicitly in SQL where appropriate. If the value arrives as text, cast it in the query with a safe expression, but only after you know it is numeric:
OFFSET $2::int. A cast will not rescue a NULL or a non-numeric string; it will just move the error. Prefer fixing the value upstream. - Check ORM pagination settings. Most ORMs and query builders accept a page and per-page count. Confirm the page index convention (0-based vs 1-based) matches what the library expects. A mismatch is a frequent source of negative offsets.
- Re-run and confirm. Execute the query again with the corrected value, then exercise the endpoint with edge cases: page 0, page 1, a huge page number, an empty parameter, and a non-numeric string. All should either return an empty result set or a clean validation error — never 2201X.
Common Mistakes
- Assuming LIMIT and OFFSET behave the same. They are separate clauses with separate checks; a valid
LIMITdoes not make an invalidOFFSETacceptable. - Passing NULL. A NULL parameter is not treated as zero. It is invalid, and the error is the same as a negative number.
- Trusting string input. Query-string parameters arrive as text.
"10"may work after an implicit cast, but""and"ten"will not. - Clamping in the wrong layer. Fixing the offset inside the SQL with
GREATEST(offset, 0)hides the bug and leaves bad data flowing through the application. - Ignoring the ORDER BY. Without a deterministic
ORDER BY, paginated results can repeat or skip rows even when the offset is valid — a separate but related pagination bug.
Tips
- Use keyset pagination (filtering on the last seen key, e.g.
WHERE id > $1 ORDER BY id LIMIT $2) for large tables. It avoids deep offsets entirely and is faster. - Validate pagination input once, at the edge of your application, and pass a typed integer down to the query layer.
- Keep the SQLSTATE in your error handling. Catching
2201Xspecifically lets you return a clear "invalid page number" message instead of a generic 500. - Add a test that sends page 0 and a negative page to every paginated endpoint.
Troubleshooting
The error appears only in production. Production likely receives user input your tests do not. Log the raw parameter value at the point it is bound and compare it with a failing request.
You cannot find the statement in the log. Increase logging detail for errors, reproduce the request, then revert the setting. On managed hosting, the logging controls live in the provider's console rather than in postgresql.conf.
The value looks correct in code but still fails. Check for a second query path — a report, export, or admin screen — that builds its own pagination. Also check middleware that rewrites query parameters.
The cast to integer throws a different error. That confirms the input is non-numeric. Fix validation upstream rather than adding more casts.
It still fails after clamping. Confirm the corrected value is actually the one being sent. A cached prepared statement or a stale build can mask the change; restart the application and retry.
Frequently Asked Questions
What causes PostgreSQL error 2201X?
The OFFSET or FETCH clause received a row count that is not a valid non-negative integer — typically a negative number, NULL, or a non-numeric string.
Is OFFSET 0 valid?
Yes. Zero is a valid row count and simply returns results from the first row. Only negative values and non-integers are rejected.
Can I use a parameter for OFFSET?
Yes, placeholders are supported, but the bound value must be an integer. Validate and convert it in your application before binding.
Does LIMIT have the same restriction?
Yes, an invalid row count in a LIMIT or FETCH clause is rejected under the same rule. Both must be non-negative integers.
Will a cast fix the error?
Only if the underlying value is a valid number in text form. A cast cannot turn NULL or "abc" into a usable offset.
How do I avoid this error entirely?
Validate pagination input at the application boundary, default missing values to 0, and consider keyset pagination for large result sets.