invalid character value for cast
SQLSTATE 22018 is raised when a character string cannot be cast to the target type because it contains a value that is not valid for that type. For example, casting the string "abc" to INTEGER.
- 1Casting or converting a string to a numeric, boolean, or date type when the string content is not valid for that type
- 2Data imported from CSV or text sources that has mixed or unexpected formats in typed columns
Casting a non-numeric string to integer.
SELECT 'not-a-number'::INTEGER;
expected output
ERROR: invalid input syntax for type integer: "not-a-number"
Fix 1
Validate and clean data before casting
WHEN When processing external data with unpredictable formats.
SELECT CASE WHEN value ~ '^[0-9]+#x27; THEN value::INTEGER ELSE NULL END FROM import_staging;
Why this works
The regex check confirms the value is all digits before the cast, returning NULL for non-numeric strings instead of an error.
Fix 2
Use a custom safe-cast function with exception handling
WHEN When a NULL-on-failure pattern is needed throughout the codebase.
CREATE OR REPLACE FUNCTION safe_int(p_val TEXT) RETURNS INTEGER AS $ BEGIN RETURN p_val::INTEGER; EXCEPTION WHEN invalid_text_representation THEN RETURN NULL; END; $ LANGUAGE plpgsql IMMUTABLE;
Why this works
The function absorbs cast failures and returns NULL, allowing bulk processing to continue past bad values.
Class 22 — Data Exception
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev