Sub topic 3
Handling values that cannot be converted
This chapter assumes you know SELECT, WHERE, CREATE TABLE, CAST, and the :: operator. A failed conversion stops the statement with an error, so you need to plan for bad input.
Handling values that cannot be converted
A cast fails when the text is not valid input for the target type. On PostgreSQL 16 and later, pg_input_is_valid returns true or false instead of raising an error:
SELECT pg_input_is_valid('42', 'integer') AS good,
pg_input_is_valid('abc', 'integer') AS bad;Inspecting pg_cast
The pg_cast catalog lists every conversion PostgreSQL knows. The castcontext column holds i (implicit), a (assignment), or e (explicit only):
SELECT castsource::regtype, casttarget::regtype, castcontext
FROM pg_cast
WHERE castsource = 'int4'::regtype
AND casttarget IN ('int8'::regtype, 'int2'::regtype);Result types in UNION, CASE and ARRAY
These constructs pick one result type for all their inputs. SELECT 1 UNION SELECT 2.5 returns numeric, because numeric can hold both values. ARRAY[1, 2.5] also produces a numeric[].
Moving values between SQL types and JSONB
A JSONB number casts directly to a numeric type. A JSON string must first be extracted as text with ->>:
SELECT ('{"n": 12, "s": "34"}'::jsonb -> 'n')::int AS from_json_number,
('{"n": 12, "s": "34"}'::jsonb ->> 's')::int AS from_json_text;Converting arrays and delimited strings
An array literal casts directly to an array type. string_to_array splits delimited text into text[], which you then cast element by element:
SELECT '{1,2,3}'::int[] AS from_literal,
string_to_array('1,2,3', ',')::int[] AS from_delimited;Casts and index usage
Casting an indexed column in a predicate hides it from a plain B-tree index. Compare the bare column to a range instead:
-- Cannot use a plain index on created_at:
SELECT * FROM events WHERE created_at::date = DATE '2026-11-27';
-- Index-friendly form:
SELECT * FROM events
WHERE created_at >= TIMESTAMP '2026-11-27'
AND created_at < TIMESTAMP '2026-11-28';Casting enums and domains
PostgreSQL has no built-in cast from an enum to boolean. CREATE CAST registers a conversion function:
Defining your own casts with CREATE CAST
CREATE TYPE yesno AS ENUM ('yes', 'no');
CREATE FUNCTION yesno_to_bool(yesno) RETURNS boolean
LANGUAGE sql IMMUTABLE AS $$ SELECT $1 = 'yes' $$;
CREATE CAST (yesno AS boolean) WITH FUNCTION yesno_to_bool(yesno);
SELECT 'yes'::yesno::boolean AS result;Exercise
Why does SELECT '3.7'::integer fail, while SELECT '3.7'::numeric::integer returns 4?
Show answer
The text '3.7' is parsed with the integer input function, which accepts only whole-number text, so it raises an error. The numeric cast first parses 3.7 as a numeric value, then rounds it to 4 when converting to integer.