Data Types and Casts
Choose and convert PostgreSQL types safely. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Search across all documentation pages
Choose and convert PostgreSQL types safely. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Prefer numeric for money; int/bigint for counters.
SELECT 1::int, 1::bigint, 1.23::numeric(10,2);
-- 1 | 1 | 1.23Store instants in timestamptz; display in a zone.
SELECT now() AT TIME ZONE 'UTC' AS utc_now;
-- utc_now: current UTC timestampGenerate UUIDs (pgcrypto/core depending on version).
SELECT gen_random_uuid();
-- e.g. 550e8400-e29b-41d4-a716-446655440000:: cast or CAST(x AS type).
SELECT '42'::int, CAST('2020-01-01' AS date);
-- 42 | 2020-01-01Curly literal or ARRAY constructor.
SELECT ARRAY[1,2,3] AS a, '{a,b}'::text[] AS t;
-- a: {1,2,3}true/false/unknown; accept t/f in text casts.
SELECT true::text, 'yes'::boolean;
-- true | trueAdd intervals to timestamps.
SELECT timestamptz '2020-01-01' + interval '7 days';
-- 2020-01-08 00:00:00+00 (zone dependent)text is preferred; varchar(n) when length limit matters.
SELECT length('hello'), char_length('hello');
-- 5 | 5Binary columns; encode for display.
SELECT encode('\xDEADBEEF'::bytea, 'hex');
-- deadbeefCreate and cast enums.
-- CREATE TYPE mood AS ENUM ('happy', 'sad');
SELECT 'happy'::mood;
-- happyConstrained alias of a base type.
-- CREATE DOMAIN email AS text CHECK (VALUE ~ '@');
-- 'a@b.co'::emailInclusive/exclusive bounds.
SELECT int4range(1, 5, '[)') @> 4;
-- t (contains 4)inet/cidr for addresses.
SELECT '10.0.0.1'::inet << '10.0.0.0/8'::cidr;
-- tjsonb is binary, indexable; prefer jsonb for storage.
SELECT '{"a":1}'::jsonb ->> 'a';
-- 1RETURN NULL on failure with try-style patterns.
SELECT nullif(trim('x'), '')::int; -- may error
-- prefer: CASE WHEN s ~ '^\d+$' THEN s::int ENDStack versions: PostgreSQL 18.4 (stable 18, maintenance 17) · pgvector 0.8+
Reviewed by Chris St. John·Last updated Jul 18, 2026