Fix PostgreSQL Error 22033 Invalid SQL JSON Subscript
In this article
PostgreSQL error 22033, "invalid sql json subscript," occurs when you attempt to access a JSON or JSONB value using a subscript (square brackets []) that does not match the expected data type of the JSON object. To fix this, you must ensure that you are using the correct operator for the data structure you are targeting—specifically, using -> or ->> for object keys and #>` or #>> for paths, rather than treating the JSON column like a native PostgreSQL array.
What You'll Need
- Access to a PostgreSQL database (version 12 or newer, as JSON subscripting syntax was introduced/refined in later versions).
- A SQL client or IDE (such as pgAdmin, DBeaver, or psql command line).
- Knowledge of whether your column is defined as the
JSONorJSONBdata type.
Step-by-Step
- Identify the Offending Query: Locate the exact SQL statement triggering the error. This error typically appears in
SELECT,UPDATE, orWHEREclauses where you are attempting to extract a value from a JSON column using square brackets, such asdata['key']. - Verify the Column Data Type: Run a describe command or check your table schema to confirm if the column is
JSONorJSONB. While both support extraction,JSONB(binary JSON) is more efficient and supports indexing, but both require specific operators for subscripting. - Check the JSON Structure: Inspect a few rows of your data to confirm if the target is a JSON Object (key-value pairs) or a JSON Array (a list of values). The subscripting error often happens when you try to use a string key to access a JSON Array, or an integer index to access a JSON Object.
- Replace Square Brackets with the Correct Operator:
- If you want to return the value as a JSON object/fragment (preserving quotes and structure), replace
column['key']withcolumn -> 'key'. - If you want to return the value as text (removing quotes), replace
column['key']withcolumn ->> 'key'.
- If you want to return the value as a JSON object/fragment (preserving quotes and structure), replace
- Handle Nested Paths: If you are trying to access a deeply nested value (e.g.,
data['user']['address']['city']), do not chain square brackets. Instead, use the path operator#>or#>>with an array of keys. For example:column #>> '{user, address, city}'. - Convert to Array if Necessary: If you genuinely intended to use PostgreSQL array subscripting, you must first cast the JSONB array to a native PostgreSQL array using
jsonb_array_elements()or a similar function. You cannot use[1]directly on a JSONB column to get the first element in the same way you do with aTEXT[]column. - Test the Query: Execute the modified query. If the error persists, check for null values in the JSON column, as attempting to subscript a NULL value can sometimes lead to unexpected behavior depending on the PostgreSQL version and the specific operator used.
Common Mistakes
One of the most frequent mistakes is treating a JSONB column as if it were a native PostgreSQL array. In standard SQL, my_array[1] is valid for an array type, but in PostgreSQL, the JSONB type is a specialized binary format. When you use column['key'], PostgreSQL may attempt to interpret this as an array subscript, but since the column is a JSONB object, it throws error 22033 because the "subscript" (the key) does not match the internal representation of the data.
Another common error is mixing up the -> and ->> operators. The -> operator returns a jsonb object. If you then try to perform a string operation (like a WHERE clause comparison with a string) on that result, the query will fail—not with error 22033, but with a type mismatch. Users often try to "fix" this by adding more brackets, which then triggers the invalid subscript error.
Finally, developers often forget that JSON arrays in PostgreSQL are 0-indexed when using the -> operator (e.g., column -> 0 gets the first element), whereas native PostgreSQL arrays are 1-indexed. Attempting to apply native array logic to JSONB data is a primary driver of this error.
Tips
To avoid these errors in the future, always default to the ->> operator when you need a value for display or comparison, as it converts the result to text immediately. If you are working with highly dynamic JSON structures where keys might be missing, use the jsonb_extract_path() function, which is often more readable than a long chain of operators.
For performance, if you find yourself frequently accessing the same JSON key, consider creating a Functional Index. Instead of querying the JSONB column directly in every WHERE clause, you can index the specific path: CREATE INDEX idx_user_city ON users ((data ->> 'city'));. This removes the need for complex subscripting during runtime and drastically speeds up lookups.
When dealing with JSON arrays, use jsonb_array_elements() to expand the array into a set of rows. This allows you to use standard SQL JOIN and WHERE logic on the individual elements rather than struggling with subscripting indices that may change as the data grows.
Troubleshooting
If you have replaced the brackets with -> or ->> and you are still seeing errors or receiving unexpected NULL results, follow these steps:
First, check for data inconsistency. Run a query to find rows where the column is not actually a JSON object: SELECT * FROM table WHERE jsonb_typeof(column) != 'object';. If some rows contain JSON arrays or plain strings instead of objects, the -> operator will return NULL or throw an error depending on the context.
Second, verify the casing of your keys. JSON keys are case-sensitive. If your data has a key named "UserID" and you query -> 'userid', PostgreSQL will not throw error 22033, but it will return NULL. This often leads developers to believe the operator is wrong when the issue is actually the key name.
Third, if you are using a programming language (like Python or Node.js) to build the query, ensure that the keys are being passed as strings. A common mistake is passing a variable that the driver interprets as an integer or a boolean, which changes how PostgreSQL interprets the subscript, potentially triggering the invalid subscript error.
Lastly, if you are using a very old version of PostgreSQL (pre-12), some of the newer subscripting shorthands are not available. Ensure your database engine is updated to a supported version to take advantage of the most stable JSONB implementations.
Frequently Asked Questions
Why does my query work in some rows but fail in others?
This usually happens because the JSON structure is inconsistent across rows. Some rows may contain an object (which supports key subscripting), while others may contain an array or a null value. When the engine hits a row where the data type doesn't match the subscript operation, it throws the error.
What is the difference between -> and ->>?
The -> operator returns the value as a jsonb object, which is useful if you need to further subscript the result. The ->> operator returns the value as text, which is necessary for comparisons, concatenations, or displaying the value in a report.
Can I use square brackets at all for JSONB?
While some newer versions of PostgreSQL have introduced limited support for square bracket syntax to align with other languages, it is strictly governed by the data type. For the vast majority of use cases, the ->, ->>, and #> operators are the standard and most reliable way to access JSON data.
How do I access the third element of a JSON array?
You should use the -> operator with an integer index. Since JSON arrays are 0-indexed, you would use column -> 2 to access the third element. If you need that element as text, use column ->> 2.
Is JSONB better than JSON for avoiding these errors?
JSONB is generally preferred because it is stored in a decomposed binary format, making access faster. While it doesn't inherently "prevent" subscript errors (since you still have to use the correct operators), it provides better support for indexing and advanced search operators that make your queries more robust.
What does the #>> operator do?
The #>> operator allows you to specify a path to a nested value using a text array. For example, data #>> '{address, city}' is equivalent to (data -> 'address') ->> 'city'. This is much cleaner for deeply nested structures.