Sub topic 10
Handling values that cannot be converted
This chapter assumes you know the cast syntaxes (CAST, ::, typed literals) and the difference between explicit and assignment casts. It covers what happens when a conversion fails, how to find the bad values, and how to convert the rest without aborting the whole statement.
What a failed conversion does
A cast that cannot convert its input raises an error. The error aborts the whole statement, so one bad row among a million fails the entire SELECT, INSERT or UPDATE. Inside a transaction block, the transaction also enters the aborted state until you roll back.
Each failure carries a SQLSTATE code that tells you the cause.
| Cause | Example | SQLSTATE | Condition name |
|---|---|---|---|
| Text is not valid for the type | `'abc'::integer` | 22P02 | invalid_text_representation |
| Value is out of range | `'99999999999'::integer` | 22003 | numeric_value_out_of_range |
| Value is too long for the type | `'abcd'` inserted into `varchar(2)` | 22001 | string_data_right_truncation |
| Date or time is malformed | `'2026-13-45'::date` | 22008 | datetime_field_overflow |
| Date or time text is unrecognized | `'tomorrow-ish'::date` | 22007 | invalid_datetime_format |
You need these codes in two places: when you catch errors in PL/pgSQL, and when you read the output of pg_input_error_info, shown below.
Some inputs that look wrong are accepted, and some that look fine are rejected. ' 8 '::integer succeeds because integer input ignores surrounding whitespace. ''::integer fails, because an empty string is not a number. '3.7'::integer also fails, because text is parsed by the integer input function and does not round.
Test a value before converting it
On PostgreSQL 16 and later, pg_input_is_valid(text, type_name) returns true or false and does not raise an error. The second function, pg_input_error_info, returns the reason a value was rejected.
SELECT pg_input_is_valid('42', 'integer') AS good,
pg_input_is_valid('abc', 'integer') AS bad;
SELECT message, sql_error_code
FROM pg_input_error_info('42000000000', 'integer');The second query returns the message value "42000000000" out of range for type integer and the code 22003. Both functions accept a type with a modifier, such as 'varchar(2)', so you can also test length limits.
Two limits matter in practice:
- Both functions are strict. A NULL input gives a NULL result, not false.
- They report errors from the type's input function. Other kinds of failure, such as a user-defined cast function that raises an error, can still throw.
Build a sample table and find the bad rows
The examples below use an import table where every column arrived as text.
CREATE TABLE raw_import (id serial PRIMARY KEY, qty text);
INSERT INTO raw_import (qty) VALUES
('12'), ('7'), (' 8 '), ('3.7'), ('abc'), (''), (NULL), ('99999999999');To list the rows that will not convert, filter on the negated check. Because the function returns NULL for a NULL qty, NOT pg_input_is_valid(...) is NULL for that row and the row would be dropped. Use IS NOT TRUE to keep NULL results visible, then exclude real NULL values on purpose.
SELECT id, qty, e.message
FROM raw_import
CROSS JOIN LATERAL pg_input_error_info(qty, 'integer') AS e
WHERE qty IS NOT NULL
AND pg_input_is_valid(qty, 'integer') IS NOT TRUE;pg_input_error_info returns one row with NULL columns for a valid value, so the filter on pg_input_is_valid is what keeps only the failures. This query gives you a data-quality report. Run it before you change a column type.
Convert the good rows and return NULL for the rest
Which approach to use depends on your version and on how much validation you need.
Option 1: pg_input_is_valid inside CASE (PostgreSQL 16+)
SELECT id,
CASE WHEN pg_input_is_valid(qty, 'integer')
THEN qty::integer
END AS qty_int
FROM raw_import;CASE returns NULL when no branch matches, and a NULL qty makes the condition NULL, which also falls through to NULL. The cast runs only for rows whose condition is true. PostgreSQL does not guarantee evaluation order between the arms of an AND, but it does guarantee that CASE only evaluates the result expression of a matching branch. The exception is constant sub-expressions, which the planner may fold early, and that does not apply to column values.
Option 2: a regular expression guard
On older versions, test the shape of the string first.
SELECT id,
CASE WHEN qty ~ '^\s*-?[0-9]{1,9}\s*$'
THEN qty::integer
END AS qty_int
FROM raw_import;The {1,9} limit keeps the value inside the integer range. A pattern like ^[0-9]+$ would let 99999999999 through and fail with error 22003. A regular expression only approximates the real input rules, so it will drift from them for types like numeric, date or timestamp. Use it only when pg_input_is_valid is unavailable.
Option 3: a function with an exception block
A PL/pgSQL EXCEPTION clause works on every version and for any conversion, including ones that pg_input_is_valid cannot check.
CREATE FUNCTION to_int_or_null(t text) RETURNS integer
LANGUAGE plpgsql IMMUTABLE AS $$
BEGIN
RETURN t::integer;
EXCEPTION
WHEN invalid_text_representation OR numeric_value_out_of_range THEN
RETURN NULL;
END;
$$;
SELECT id, qty, to_int_or_null(qty) AS qty_int FROM raw_import;A block with an EXCEPTION clause starts a subtransaction each time it runs. That cost is small for a few rows and becomes noticeable over millions. Catch only the conditions you expect. A bare WHEN OTHERS would also hide unrelated problems, such as a query cancel.
Choosing an approach
Fix the data permanently
Once you know which rows are bad, decide what each bad value means. Common choices are to convert an empty string to NULL, strip known noise, or move the row to a rejects table. NULLIF handles the empty-string case without any test:
SELECT id, NULLIF(trim(qty), '')::integer AS qty_int
FROM raw_import
WHERE qty IS DISTINCT FROM 'abc'
AND qty IS DISTINCT FROM '3.7'
AND qty IS DISTINCT FROM '99999999999';That filter is only for illustration. In real work, correct or quarantine the rows instead of listing exclusions. After cleanup, change the column type with a USING clause so the conversion is explicit and applied to every row:
ALTER TABLE raw_import
ALTER COLUMN qty TYPE integer
USING CASE WHEN pg_input_is_valid(qty, 'integer') THEN qty::integer END;The statement runs in one transaction and fails as a whole if any row raises an error. It also takes an ACCESS EXCLUSIVE lock and rewrites the table, so on a large table plan it for a maintenance window. Silently turning bad values into NULL loses information, so run the report query first and keep the rejected values somewhere.
Common mistakes
- Treating
pg_input_is_validas false for NULL input. It returns NULL, andNOT NULLis still NULL. - Using a regular expression that does not check range, so overflow errors still occur.
- Wrapping every conversion in an exception block in a hot query, which adds a subtransaction per row.
- Using
WHEN OTHERSand hiding errors that are not conversion problems. - Assuming
'3.7'::integerrounds. Cast throughnumericfirst:'3.7'::numeric::integergives 4.
Exercise
A table t(v text) contains '10', '2e3', ' 5', 'x1' and NULL. Write a query that returns each v with an integer column that is the converted value, or NULL when the text is not a valid integer. Which of the five values convert, and why does the query not fail on the others?
Show answer
SELECT v, CASE WHEN pginputisvalid(v, 'integer') THEN v::integer END AS vint FROM t; The values '10' and ' 5' convert, giving 10 and 5, because integer input accepts surrounding whitespace. '2e3' is rejected because integer input does not accept exponent notation. 'x1' is rejected as invalid syntax. NULL gives NULL because the check returns NULL. The query does not fail because CASE evaluates the cast only for rows where the check returned true.