CAST converts a value from one PostgreSQL data type to another.
CAST quickly converts one data type to another, allowing accurate comparisons, calculations, and storage in PostgreSQL.
Use either the functional form CAST(expression AS target_type)
or the shorthand expression::target_type
. Both return the value in the new data type.
Wrap the text literal or column in CAST
. Example: SELECT CAST('42' AS integer);
. Shorthand: SELECT '42'::int;
.Ensure the string is numeric to avoid runtime errors.
Strip the time portion by casting: SELECT NOW()::date;
. PostgreSQL drops the hour, minute, and second, returning only the calendar date.
Yes. Example: INSERT INTO sales (amount) VALUES (CAST($1 AS numeric));
.This keeps client-side strings from polluting numeric columns.
Validate data before casting, use NULLIF
to handle blanks, and prefer explicit CAST
in mission-critical code for clarity and future maintainability.
SELECT CAST(NULLIF(raw_text, '') AS numeric) FROM staging;
avoids errors when raw_text
is empty.
Use the same syntax: SELECT '{1,2,3}'::int[];
or SELECT CAST('{"a":1}' AS jsonb);
.Ensure the literal follows array or JSON rules.
Performance is identical; both compile to the same plan. Choose the style that improves readability for your team.
Cast explicitly in migrations, check input validity, specify length when casting to varchar
, and monitor for overflow or precision loss.
.
No. CAST only affects the returned value. To persist the new type, update the column or use ALTER TABLE.
Minor. PostgreSQL applies a type conversion function, which is negligible for small datasets but can add up in large joins. Pre-convert columns when possible.
Yes. Use CREATE CAST
to define conversions between user-defined types and built-in types.