PostgreSQL Error 22011: Substring Error Fix
In this article
PostgreSQL error 22011 (substring error) means a substring or similar function was called with an invalid start position or length - most often a negative start index, a negative length, or a start position of zero. The fix is to validate the arguments before the call: use GREATEST/LEAST to clamp values, guard with CASE, or switch to a function that tolerates out-of-range input. No server restart or configuration change is required.
What You'll Need
- Access to a PostgreSQL client (psql, pgAdmin, DBeaver, or your application's query runner) with permission to run SELECT statements on the affected table.
- The exact query or application code that triggers the error, including the substring/substr/left/right/overlay call.
- A sample of the input data that reproduces the problem (or the ability to query it).
- Basic familiarity with SQL expressions and, if the error comes from application code, access to that code.
Step-by-Step
- Reproduce the error and capture the full message. Run the failing statement in psql or your client. PostgreSQL returns something like
ERROR: negative substring length not allowedorERROR: substring start index cannot be zeroalongside SQLSTATE 22011. The wording tells you which argument is invalid: a negative length, a zero start, or a start beyond the string. If the error appears only in application logs, copy the exact SQL and parameters from the log entry. - Identify the offending expression. Look for
substring(),substr(),left(),right(),overlay(), orposition()combined with arithmetic. Common culprits aresubstring(col from pos for len)whereposorlencomes from another column or a calculation, andleft(col, n)wherenis negative. If the query is long, bisect it: comment out parts until the error disappears, then re-add them one at a time. - Inspect the actual argument values. Run a SELECT that shows the inputs without calling the substring function, for example
SELECT pos, len, col FROM your_table WHERE pos <= 0 OR len < 0;. This confirms whether the problem is bad data, a bad calculation, or a hard-coded constant. If the values look valid but the error persists, check for implicit casts - a text column compared or concatenated with an integer can produce unexpected numbers. - Clamp the arguments in the query. The quickest fix is to force the arguments into a valid range. For a start position, use
GREATEST(pos, 1); for a length, useGREATEST(len, 0). For example:substring(col from GREATEST(pos, 1) for GREATEST(len, 0)). This turns an error into an empty string or a shorter result, which is usually the intended behaviour when data is incomplete. - Guard with CASE where clamping changes meaning. If a zero or negative length should return NULL rather than an empty string, wrap the call:
CASE WHEN len < 0 OR pos < 1 THEN NULL ELSE substring(col from pos for len) END. Decide explicitly what the business rule is - empty string, NULL, or skip the row - and encode that rather than relying on the error. - Fix the source data or calculation. If the invalid values come from a column, find out why. Check for rows where a computed offset is negative, where a length is derived by subtracting a larger number from a smaller one, or where a text field was cast to integer and produced zero. Correct the upstream expression or clean the data with an UPDATE, and add a CHECK constraint (for example
CHECK (len >= 0)) so bad values cannot be inserted again. - Handle it in application code if the query is generated there. If your ORM or query builder constructs the substring call, validate the parameters before binding them. Reject negative lengths and start positions below 1 at the boundary, or normalise them the same way as step 4. This prevents the error from reaching the database at all and gives you a clearer application-level message.
- Verify the fix against the original failing input. Re-run the exact statement or application action that failed. Then test edge cases: empty string, NULL, start position 1, start position equal to length plus one, and length 0. Confirm the results match your intended rule (empty string, NULL, or truncated text) rather than merely not erroring.
- Check for the same pattern elsewhere. Search your schema and codebase for other substring-style calls with computed arguments. Error 22011 often appears in several places at once when a shared calculation or data source is wrong, so fixing one query may leave others waiting to fail.
Common Mistakes
- Assuming the error is a PostgreSQL bug. SQLSTATE 22011 is a data exception raised by invalid arguments; the server is behaving correctly. Look at the inputs, not the version.
- Using a start position of 0. PostgreSQL substring positions are 1-based. A start of 0 raises the error; a start greater than the string length returns an empty string instead.
- Clamping the length but not the start. Both arguments can be invalid independently. Fix both in the same expression.
- Silently swallowing the error with a catch-all exception handler. That hides bad data and makes later results wrong. Fix the argument or the data instead.
- Forgetting NULL. If any argument is NULL, the result is NULL, not an error - so a NULL check alone will not explain a 22011.
- Changing the query but not the data. If the invalid values are stored in a column, the next insert or the next report will fail again unless the source is corrected or constrained.
Tips
- Prefer
left()andright()when you only need a prefix or suffix; they are clearer than substring with a computed length and less prone to argument mistakes. - Use
char_length()to check a string's length before slicing, especially when the length comes from user input or another system. - Add CHECK constraints or a validation layer at the point where lengths and offsets are calculated, so invalid values are rejected early.
- When debugging, select the arguments as separate columns next to the failing expression; seeing the raw numbers usually makes the cause obvious.
- Remember that labels and function names can differ slightly between PostgreSQL versions and client tools; the SQLSTATE 22011 code is the reliable identifier.
Troubleshooting
- The error persists after clamping. Confirm you edited the expression that actually runs - a view, a function, or a generated query may contain a copy of the original call. Check the server log for the exact statement PostgreSQL received.
- The error only appears for some rows. That points to data-dependent arguments. Query the table for rows where the computed start is below 1 or the length is negative, and inspect those rows.
- The error comes from a stored procedure or trigger. Reproduce it by calling the procedure with the same parameters, then inspect the internal expression. You may need to add validation inside the procedure rather than at the call site.
- You cannot change the query (third-party application). Fix the data so the arguments are always valid, or add a view with clamped expressions and point the application at the view if that is supported.
- The message mentions a different function than expected. Functions such as
overlay()andposition()can also raise 22011-style errors through their arguments. Search the statement for all string functions, not just substring.
Frequently Asked Questions
What does PostgreSQL error 22011 mean?
It is SQLSTATE 22011, a data exception indicating an invalid argument to a substring-type function - typically a negative length or a start position of zero or less.
Is error 22011 caused by a corrupted database?
No. It is raised when a function receives an invalid argument, usually from computed values or bad data, not from storage corruption.
Does a start position of 0 always fail?
Yes. PostgreSQL substring positions are 1-based, so 0 is invalid and raises the error; positions beyond the string length return an empty string.
What is the difference between substring and substr here?
Both accept a start and length and both can raise 22011 for invalid arguments. The argument rules are the same; the difference is mainly syntax and portability.
Can I prevent 22011 with a CHECK constraint?
You can prevent invalid stored values, such as negative lengths, with CHECK constraints. Arguments computed at query time still need clamping or validation in the query or application.
Will upgrading PostgreSQL fix it?
No. The error reflects invalid input, not a version defect. Fix the arguments or the data instead.