Error
Error Code: 22018

PostgreSQL Error 22018: Invalid Character Cast Value

📦 PostgreSQL
📋

Description

This error indicates that an attempt was made to convert a string or character value to another data type (e.g., numeric, date, boolean), but the source value's format is incompatible with the target type. It commonly occurs during data insertion, updates, or explicit type casting operations.
💬

Error Message

invalid character value for cast
🔍

Known Causes

4 known causes
⚠️
Mismatched Data Format
The character string being cast does not conform to the expected format of the target data type (e.g., trying to cast 'hello' to an integer).
⚠️
Invalid Date/Time String
A character string intended for a DATE, TIME, or TIMESTAMP type contains an invalid date or time format (e.g., '2023-13-01' or 'Feb 30, 2023').
⚠️
Non-Numeric Characters in Numeric Cast
Attempting to cast a string that includes non-numeric characters (other than an optional sign or decimal point) to a numeric data type like INTEGER or NUMERIC.
⚠️
Locale-Specific Formatting Issues
The character value uses a decimal separator or date format that is not recognized by the current database locale when casting to a numeric or date type.
🛠️

Solutions

4 solutions available

1. Identify and Correct Invalid Data medium

Locate and fix the specific data causing the cast error.

1
Identify the table and column involved in the cast operation. This often requires examining the query that produced the error. If the error message provides context, use that to pinpoint the location.
2
Examine the data in the identified column. Look for values that do not conform to the target data type. For example, if casting to an integer, look for non-numeric characters or values that are too large/small.
SELECT column_name FROM table_name WHERE ...; -- Replace 'column_name' and 'table_name' and add a WHERE clause to filter for potentially problematic data.
3
Correct the invalid data. This might involve updating the offending rows with valid values, or in some cases, removing them if they are not critical.
UPDATE table_name SET column_name = 'corrected_value' WHERE id = offending_id; -- Replace with actual values and conditions.
4
Re-run the query that caused the error to confirm the issue is resolved.

2. Use a Safe Casting Function easy

Employ functions that handle potential errors gracefully during casting.

1
Instead of direct casting (e.g., `column_name::integer`), use `NULLIF` or `CASE` statements to handle invalid values. `NULLIF(value, invalid_value)` will return NULL if the value matches the invalid_value. A `CASE` statement allows more complex conditional logic.
SELECT NULLIF(column_name, 'invalid_string')::integer FROM table_name; -- Example for a string that should be an integer
2
For more complex scenarios where multiple invalid values might exist or you want to return a default value, use a `CASE` statement.
SELECT CASE WHEN column_name ~ '^\d+$' THEN column_name::integer ELSE NULL END FROM table_name; -- Example: only cast if it looks like a number
3
Consider using `to_number` for numeric casts, which can provide better error handling or allow for specific formats.
SELECT to_number(column_name, '99999') FROM table_name; -- Example for a numeric string

3. Pre-process or Cleanse Data Before Casting medium

Cleanse the data before attempting the cast.

1
If the invalid characters are consistent (e.g., currency symbols, commas, extra spaces), use string manipulation functions to remove them before casting.
SELECT translate(column_name, '$,', '')::numeric FROM table_name; -- Removes '$' and ',' before casting to numeric
2
Use regular expressions to strip out unwanted characters. For example, to keep only digits:
SELECT regexp_replace(column_name, '[^0-9]', '', 'g')::integer FROM table_name; -- Removes all non-digit characters
3
Combine these cleaning steps with safe casting functions for a robust solution.
SELECT CASE WHEN regexp_replace(column_name, '[^0-9]', '', 'g') ~ '^\d+$' THEN regexp_replace(column_name, '[^0-9]', '', 'g')::integer ELSE NULL END FROM table_name;

4. Validate Data Type Expectations advanced

Ensure the data actually conforms to the intended target data type.

1
Review the schema definition and the intended use of the column. Is the target data type appropriate for the data being stored?
2
If the data is inherently unstructured or can contain non-conforming values, consider using a more flexible data type like `TEXT` or `VARCHAR` and performing validation and conversion in your application logic or during ETL processes.
3
For very large datasets, consider creating a temporary table with a cleaned version of the data, performing the cast there, and then joining back to the original table if necessary. This can be more performant than row-by-row cleaning.
CREATE TEMP TABLE cleaned_data AS SELECT id, regexp_replace(column_name, '[^0-9]', '', 'g')::integer AS cleaned_column FROM original_table WHERE ...;
🔗

Related Errors

5 related errors