Diagnostic Queries
Symptoms
A substring()/substr() call was given a negative length. Length must be non-negative, so PostgreSQL raises SQLSTATE 22011 (substring_error).
- The length argument to substring is negative.
- Common with computed lengths (e.g. position arithmetic).
- Negative length has no defined meaning.
What the server log shows
ERROR: negative substring length not allowed
Why PostgreSQL raises this — what the manual says
As Section 9.4 String Functions and Operators explains:
The count (length) argument to substring() must not be negative; a negative length has no meaning and is rejected — pass zero or a positive length, or omit the FOR clause to return the rest of the string.
substring reads length characters from the start position. A negative length is meaningless (you cannot read a negative number of characters), so PostgreSQL rejects it with 22011.
Common causes
- A computed length that became negative (e.g.
end - startwith end < start). - Off-by-one or sign errors in length arithmetic.
- Unvalidated length input.
How to fix it
- Clamp the length to be non-negative (e.g.
GREATEST(len, 0)). - Fix the arithmetic so length is never negative.
- Validate position/length inputs before calling substring.
Related & next steps
Reference: PostgreSQL 18 Section 9.4 “String Functions”.
Thanks — noted. This helps keep the database accurate.