SQLSTATE 22011Severity lowLab verified

Incident brief

Negative substring length not allowed

substring(... FOR count) was given a negative count. PostgreSQL treats a negative substring length as a data error rather than returning an empty string.

Reproduced on PostgreSQL 16.14Verified 2026-07-19 (isolated lab, PostgreSQL 16.14)Reviewed by Verified against PostgreSQL 16.14 in an isolated lab environment

In 10 seconds

What
Negative substring length not allowed
What triggers it
Call substring() with a FOR length that evaluates to a negative number.
The fix
Clamp the length to zero with GREATEST(len, 0) so a computed negative can never reach substring().
Proof
Reproduced on PostgreSQL 16.14 → substring('postgresql' FROM 3 FOR -2) was rejected with SQLSTATE 22011. Clamping the length to zero with GREATEST returned an empty string instead of erroring.

The fix

What to do right now

The immediate, application-level response to this error.

  • Clamp the length to zero with GREATEST(len, 0) so a computed negative can never reach substring().
  • Validate or recompute the length in application code before building the query.
  • Prefer left()/right() when you actually want a fixed number of leading or trailing characters.
Fix — SQL
-- clamp a possibly-negative length to zero instead of raising 22011
SELECT substring('postgresql' FROM 3 FOR GREATEST(-2, 0)) AS safe_empty;

Related & next steps

Follow the thread

Everything this error touches — jump straight to the sibling error, term, runbook, or parameter.

Verification

PG 16.14
Last verified
2026-07-19 (isolated lab, PostgreSQL 16.14)
Reviewed by
Verified against PostgreSQL 16.14 in an isolated lab environment
Audit status
reviewed