How to diagnose and fix the 22011 substring_error error code in Postgres.

The 22011 error code in PostgreSQL, labeled as substring_error, typically occurs when there is an issue with the arguments provided to the SUBSTRING function. This function is used to extract a substring from a string, and it requires that the starting position and the length of the substring are within the bounds of the given string.

To diagnose and fix the 22011 error code:

  1. Check the arguments passed to the SUBSTRING function to ensure the starting position is not less than 1, as string indexing in PostgreSQL starts at 1.
  2. Make sure the length of the substring, when added to the starting position, does not exceed the total length of the string.
  3. Confirm that the arguments are of the correct data type (e.g., integer for the position and length).

Here’s an example of a SUBSTRING function that might cause a 22011 error:


In this case, the string ‘PostgreSQL’ has a length of 11 characters, but the SUBSTRING function is trying to extract a substring starting at position 5 with a length of 20 characters, which goes beyond the end of the string.

To fix this, you would adjust the starting position and length to ensure they are within the bounds of the string:


This corrected SUBSTRING call starts at position 5 and extracts 7 characters, resulting in the substring ‘greSQL’, which is within the bounds of the original string.

If you encounter the 22011 error, review the use of the SUBSTRING function in your SQL query and adjust the start position and length parameters accordingly to ensure they are within the correct range of the string you are working with.

For more information on error codes and string functions in PostgreSQL, you can refer to the PostgreSQL documentation on error codes and the PostgreSQL documentation on string functions.

Leave a Comment