PG
PRO
22011ERRORTier 2 — Caution✅ HIGH confidence

substring error

Category: Data ExceptionVersions: All Postgres versions

What this means

SQLSTATE 22011 is raised when arguments to the SUBSTRING function are invalid — for example, a negative or zero length argument in contexts where the standard requires validation.

Why it happens

  1. 1Invalid from/for arguments to SUBSTRING that violate the SQL standard length requirements

How to reproduce

SUBSTRING with an invalid length argument.

trigger — this will ERROR
SELECT SUBSTRING('hello' FROM 2 FOR -1);
ERROR: negative substring length not allowed

Fix 1: Ensure SUBSTRING arguments are non-negative

When using SUBSTRING with computed arguments.

fix
SELECT SUBSTRING('hello' FROM 2 FOR GREATEST(len_val, 0));

Why this works

GREATEST clamps the length to 0 or above. A FOR 0 returns an empty string, which is usually safer than an error.

Sources

📚 Official docs: https://www.postgresql.org/docs/current/errcodes-appendix.html

🔧 Source ref: Class 22 — Data Exception

Confidence assessment

✅ HIGH confidence

Standard SQLSTATE for SUBSTRING argument validation. Stable across versions.

See also

📄 Reference pages

String FunctionsSUBSTRING
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →