Part 03 / Topic 8 of 9
Type casting
Postgres converts between types with CAST(value AS type) — or its own beloved shorthand :::
SELECT '120'::numeric AS now_a_number,
CAST('2025-04-20' AS date) AS now_a_date,
42::text AS now_text,
'42 items'::text AS stayed_text;
now_a_number | now_a_date | now_text | stayed_text
--------------+------------+----------+-------------
120 | 2025-04-20 | 42 | 42 items
(1 row)
Casts validate — garbage is rejected, loudly:
SELECT 'not a number'::numeric;
ERROR: invalid input syntax for type numeric: "not a number"
LINE 1: SELECT 'not a number'::numeric;
^
That error at write time is the whole point of types: better a red message today than a corrupted report next quarter. You have been using casts all along (7::numeric / 3, date_trunc(...)::date) — now you know their name.
🧪 Quick quiz — answer from memory, then check.
- Two ways to cast text to a date?
- What happens when a cast can't parse the value?
Show the answers
CAST('2025-04-20' AS date)and'2025-04-20'::date.- An error — casts validate rather than guessing.
Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.