Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

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.

  1. Two ways to cast text to a date?
  2. What happens when a cast can't parse the value?
Show the answers
  1. CAST('2025-04-20' AS date) and '2025-04-20'::date.
  2. An error — casts validate rather than guessing.

Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.

Search the guide