Fix PostgreSQL Error 2203b SQL JSON Number Not Found
In this article
PostgreSQL error 2203b occurs when a query attempts to extract a value from a JSONB or JSON column using a numeric operator or function, but the value found at that path is not a valid number or the path does not exist. To fix this, you must ensure that the JSON path is correct and that you are using the appropriate operator (such as #> for objects or #>{index} for arrays) followed by a proper type cast to numeric or integer.
What You'll Need
- Access to a PostgreSQL database instance (via psql, pgAdmin, or another SQL client).
- Administrative or read/write permissions for the table containing the JSON data.
- A basic understanding of JSON structure (objects vs. arrays).
- Knowledge of the specific JSON keys or array indices you are trying to target.
Step-by-Step
- Identify the Failing Query: Locate the exact SQL statement triggering the 2203b error. This usually happens during a
SELECTstatement involvingjsonb_extract_path, the#>operator, or when using the->>operator in combination with a mathematical operation. - Verify the JSON Path: Check the data in the column for the specific row causing the crash. Use a simple
SELECT column_name FROM table_name WHERE id = [target_id]to see the raw JSON. Confirm that the key you are referencing actually exists. If you are targeting an array, ensure the index (which is 0-based in PostgreSQL JSON) is within the actual bounds of the array. - Check for Data Type Mismatches: The 2203b error often triggers when the database expects a number but finds a string, a boolean, or a null value. For example, if your JSON is
{"price": "10.00"}(a string) instead of{"price": 10.00}(a number), a direct numeric extraction may fail depending on the function used. - Switch to the Text Extraction Operator: Instead of using operators that attempt to return a JSON numeric type, use the
->>operator. This operator returns the value as text, which is much more resilient. For example, instead of trying to extract a number directly, usedata->>'price'. - Apply Explicit Type Casting: Once you have extracted the value as text, cast it to the desired numeric type. This allows PostgreSQL to handle the conversion more gracefully. The syntax should look like:
(data->>'price')::numeric. This tells the engine to take the text representation and attempt to convert it into a number. - Implement NULL Handling: If some rows lack the numeric key entirely, the cast might still fail or return nulls that break subsequent calculations. Wrap your extraction in a
COALESCEfunction to provide a default value. Example:COALESCE((data->>'price')::numeric, 0). - Validate with a WHERE Clause: To prevent the error from recurring on dirty data, add a filter to your query that only processes rows where the value is actually numeric. You can use the
jsonb_typeof()function to verify the type before attempting the cast. Example:WHERE jsonb_typeof(data->'price') = 'number'. - Test the Query on a Subset: Run the modified query on a small sample of data (e.g.,
LIMIT 100) to ensure the 2203b error no longer appears and that the numeric values are being calculated correctly.
Common Mistakes
One of the most frequent mistakes is confusing the -> operator with the ->> operator. The -> operator returns a JSON object or array (a jsonb type), while ->> returns the value as a text string. If you try to perform math on the result of ->, PostgreSQL will throw an error because you cannot add or multiply a JSON object, even if that object contains a number.
Another common error is forgetting that JSON arrays in PostgreSQL are 0-indexed. If you have an array with three elements and you attempt to access index 3 (the fourth position), the system will return a null or throw a path error, which can cascade into a 2203b error if that result is then passed into a numeric function.
Users also frequently forget to handle "quoted numbers." In JSON, 123 is a number, but "123" is a string. If your data ingestion process wrapped numbers in quotes, they are technically strings. Attempting to use JSON-specific numeric functions on these strings will trigger a type mismatch error.
Tips
For high-performance queries on large datasets, avoid casting JSON values in the WHERE clause. Casting (data->>'price')::numeric on every row during a scan will slow down your query significantly. Instead, consider creating a Functional Index. You can create an index on the casted value: CREATE INDEX idx_price ON table (( (data->>'price')::numeric ));. This allows PostgreSQL to search the numeric values without parsing the JSON for every single row.
When dealing with deeply nested JSON, use the #> operator with a path array. For example, data#>'{orders, 0, price}' is much cleaner than chaining multiple -> operators. Just remember that #> returns a JSON object, so you will still need to use #>> to get the text value before casting to a number.
Always use JSONB instead of JSON for your column types if possible. JSONB stores data in a decomposed binary format, which makes extraction and indexing significantly faster than the plain JSON type, which must be re-parsed on every access.
Troubleshooting
If you have applied the cast and are still seeing errors, the most likely cause is "dirty data." This means some of your JSON fields contain non-numeric characters (like currency symbols or commas) that cannot be cast to a number. To find these problematic rows, run a query using a regular expression to find any value in that field that contains characters other than digits and decimals: SELECT * FROM table WHERE data->>'price' !~ '^[-+]?[0-9]*\.?[0-9]+$'.
If the query returns rows, you must clean the data before casting. You can use the regexp_replace function to strip out non-numeric characters. For example, regexp_replace(data->>'price', '[^0-9.]', '', 'g')::numeric will remove everything except numbers and periods before attempting the conversion.
If you are using a very old version of PostgreSQL, some of the newer JSONB operators may not be available. Check your version using SELECT version();. If you are on a version older than 9.4, you will have very limited JSON support and should consider upgrading to leverage JSONB and the associated numeric extraction tools.
Frequently Asked Questions
Why does the error say "number not found" when the number is clearly there?
This usually happens because the database sees the value as a JSON string (wrapped in quotes) rather than a JSON number. To the engine, a string is not a number, regardless of the characters inside the string.
What is the difference between -> and ->>?
The -> operator returns a jsonb object, which is useful if you want to keep drilling down into more nested keys. The ->> operator returns the value as text, which is necessary for casting to integers or decimals.
Can I use this to extract numbers from a JSON array?
Yes. You can use data->0 to get the first element as JSON, or data->>0 to get the first element as text. If the array contains numbers, you would then cast that result to ::numeric.
Is it better to store numbers as strings in JSON?
Generally, no. Storing numbers as actual JSON numbers (without quotes) is more efficient for storage and allows for better use of JSON-specific numeric functions. However, if you need extreme precision (like 20+ decimal places), storing them as strings and casting them to numeric in SQL is safer to avoid floating-point rounding errors.
Does COALESCE fix the 2203b error?
COALESCE prevents errors caused by NULL values being passed into functions that don't accept them, but it does not fix the 2203b error itself. You must first successfully extract the value as text and cast it; COALESCE then handles the case where the key was missing entirely.