Memra

Types & casting

◈ 2 cards

The core types, and converting between them.

Pick the right type

Postgres is strongly typed. The everyday types:

  • int / bigint — whole numbers; numeric(p,s) — exact decimals (money!); real/double precision — floats
  • text / varchar(n) — strings
  • boolean — true/false
  • date, timestamp, timestamptz, interval — time
  • uuid, json/jsonb, arrays — covered next

Convert with ::type (or CAST(x AS type)):

SELECT '42'::int, 3.7::int, 'true'::boolean, now()::date;
expressionresulttype'42'::int + 850integerround(3.7)::int4integer'yes'::booleantrueboolean14.99::int15integer — it rounds0.1::float8 + 0.2::float80.30000000000000004never for moneyprice::int rounds. Float arithmetic drifts.
Casting is not truncation: 14.99::int is 15, not 14. And the last row is why money is numeric — the drift is in the binary representation itself, so no amount of rounding at the end recovers the lost cents.
NORMAL ~/memra/learn/postgresql/data-types-and-casting utf-8 LF