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.

What lands in your log

ERROR: negative substring length not allowed

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

In 10 seconds

What triggers it
Call substring() with a FOR length that evaluates to a negative number.
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.

Fix

What to do right now

Application-level steps for 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;

Connected

Everything this error touches

Every page this SQLSTATE connects to: the concept that explains it, the runbooks that fix it, the parameters you tune to prevent it, and the sibling errors it travels with. All real cross-references. Jump straight in, or open the full interactive map.

Open in the interactive map →

Verification

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

Went further?

Pro unlocks the second lab proof

Free page stops the bleeding. Pro adds the operational test, SQLSTATE audit, and deeper evidence, same error, more certainty.

FollowSubstackLinkedInnew errors · lab notes · hiring loops