SQLSTATE 22011 ERROR Class 22: Data Exception

substring_error negative substring length not allowed — 22011

PostgreSQL error "negative substring length not allowed" (SQLSTATE 22011): what it means, common causes, and how to fix it.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

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 - start with end < start).
  • Off-by-one or sign errors in length arithmetic.
  • Unvalidated length input.

How to fix it

  1. Clamp the length to be non-negative (e.g. GREATEST(len, 0)).
  2. Fix the arithmetic so length is never negative.
  3. Validate position/length inputs before calling substring.

Related & next steps

Reference: PostgreSQL 18 Section 9.4 “String Functions”.

Was this helpful?