Sub topic 8
Casting values between types
This chapter assumes you can write basic SELECT and INSERT statements and run them in psql. It also assumes you have met the main built-in types: integers, numeric, text, dates and jsonb. It covers how PostgreSQL converts a value from one type to another, which conversions happen without being asked, and which errors to expect.
Explicit casts
An explicit cast converts a value to a type you name. PostgreSQL offers three equivalent spellings:
SELECT '42'::integer + 1 AS shorthand,
CAST('42' AS integer) + 1 AS standard,
integer '42' + 1 AS typed_literal;:: is PostgreSQL-specific. CAST(x AS type) is standard SQL and works in other databases. The typed-literal form, integer '42', works only for a constant.
The :: operator binds tighter than arithmetic operators. In a + b::integer, only b is cast. Use parentheses when you want the whole expression converted:
SELECT (1.6 + 2.6)::integer AS rounded_sum; -- 4Three kinds of cast
Each cast is registered in the system catalog pg_cast with a context that says where PostgreSQL may apply it on its own.
| Context | `castcontext` | When PostgreSQL applies it |
|---|---|---|
| Implicit | `i` | Anywhere, automatically, for example in operators and function arguments |
| Assignment | `a` | Also when storing a value in a column (`INSERT`, `UPDATE`) |
| Explicit | `e` | Only when you write `::` or `CAST` |
You can inspect the rules yourself:
SELECT castsource::regtype AS source,
casttarget::regtype AS target,
castcontext
FROM pg_cast
WHERE castsource = 'integer'::regtype
ORDER BY casttarget::regtype::text;Widening conversions such as integer to bigint or numeric are implicit. Narrowing or lossy ones, such as integer to smallint, are assignment-only. Unusual ones, such as integer to boolean, are explicit-only. This is why 1 + 1.5 works but a text column cannot be added to an integer column:
SELECT 1 + 1.5 AS ok; -- 2.5, integer widened to numeric
SELECT 1 + '2'::text AS fails; -- ERROR: operator does not exist: integer + textConversions between text and most other types are not in pg_cast as ordinary entries. PostgreSQL performs them with each type's input and output functions, and any type can be cast to text with an explicit cast.
flowchart TD
A[Value of type A needed as type B] --> B{Same type?}
B -- yes --> Z[Use as is]
B -- no --> C{Is an explicit cast written?}
C -- yes --> D[Apply cast of any context]
C -- no --> E{Storing into a column?}
E -- yes --> F[Apply implicit or assignment cast]
E -- no --> G[Apply implicit cast only]
D --> H{Cast exists and value is valid?}
F --> H
G --> H
H -- yes --> Z
H -- no --> X[Error]The diagram above has a caption and alt text in the block below it so screen readers can describe it.
Unknown literals
A quoted literal such as '42' starts with the pseudo-type unknown. PostgreSQL resolves it from context instead of treating it as text. That is why 1 + '2' works while 1 + '2'::text fails: the bare literal becomes an integer, and the explicitly typed text value cannot.
Resolution happens once, when the query is parsed. A literal that is not valid for its resolved type fails with an input error:
SELECT 'abc'::integer;
-- ERROR: invalid input syntax for type integer: "abc"Common errors
Casting fails in two main ways.
- Invalid input. The text does not parse as the target type, as in
'abc'::integer,'2026-02-30'::date(date/time field value out of range) or'{bad'::jsonb. - Out of range. The value parses but does not fit, as in
3000000000::integer(integer out of range) or100000::numeric(5,2)(numeric field overflow).
PostgreSQL has no TRY_CAST. Since PostgreSQL 16 you can test a conversion first with pg_input_is_valid:
SELECT pg_input_is_valid('42', 'integer') AS good,
pg_input_is_valid('abc', 'integer') AS bad; -- true, falseOn older versions, validate with a regular expression in a CASE expression, or write a function that catches the error.
Rounding and truncation
Casting between numeric types rounds, but the rule depends on the source type:
SELECT 2.5::numeric::integer AS from_numeric, -- 3, half away from zero
2.5::double precision::integer AS from_float, -- 2, half to even
7 / 2 AS int_division, -- 3
7::numeric / 2 AS exact_division; -- 3.5000000000000000Integer division discards the fraction. Cast at least one operand to numeric before dividing.
Length limits behave differently depending on how the value arrives:
SELECT 'abcdef'::varchar(3) AS explicit_cast; -- abc, silently truncated
CREATE TABLE codes (code varchar(3));
INSERT INTO codes VALUES ('abcdef');
-- ERROR: value too long for type character varying(3)An explicit cast to varchar(n) truncates. An assignment into a varchar(n) column raises an error instead. The standard exception is trailing spaces, which are accepted and trimmed.
Casts that depend on settings
Some conversions use session settings, so the same text can produce different results on different connections:
SET DateStyle = 'ISO, MDY';
SELECT '01/02/2026'::date; -- 2026-01-02 (January 2)
SET DateStyle = 'ISO, DMY';
SELECT '01/02/2026'::date; -- 2026-02-01 (February 1)Text to timestamptz also depends on the session TimeZone when the text has no offset. Write dates in ISO 8601 format (2026-01-02) and include an offset for instants (2026-01-02 12:00:00+00). Both forms are unambiguous under any setting.
Converting a timestamptz to a local wall-clock time is not a cast. Use AT TIME ZONE:
SELECT '2026-01-15 12:00:00+00'::timestamptz AT TIME ZONE 'America/New_York' AS new_york_local;
-- 2026-01-15 07:00:00Casting JSON values
The ->> operator returns text, so you need a cast to compare numerically. In PostgreSQL 11 and later, a jsonb scalar can also be cast directly to a number or boolean:
SELECT ('{"qty": "5"}'::jsonb ->> 'qty')::integer + 1 AS from_text, -- 6
('{"qty": 5}'::jsonb -> 'qty')::integer + 1 AS from_jsonb; -- 6Without the cast, payload ->> 'qty' > 10 compares text, so '9' sorts after '10'.
Casts and indexes
Casting a column inside a WHERE clause usually prevents an index on that column from being used, because the index stores the original values:
-- Cannot use a plain index on created_at
SELECT * FROM orders WHERE created_at::date = '2026-01-15';
-- Can use it
SELECT * FROM orders
WHERE created_at >= '2026-01-15' AND created_at < '2026-01-16';The same applies to id::text = '42'. Cast the constant, not the column. Alternatively, create an expression index on the exact expression you query.
Checklist
- Prefer
CASTin portable SQL and::in PostgreSQL-only code, and wrap whole expressions in parentheses. - Expect implicit casts only for widening conversions.
- Handle invalid input and out-of-range errors where untrusted text enters the database.
- Use ISO formats for dates and timestamps.
- Keep casts off indexed columns in
WHEREclauses.
Exercise
What does SELECT 5 / 2, 5::numeric / 2, 2.5::double precision::integer; return, and why does the third value differ from 2.5::numeric::integer?
Show answer
It returns 2, 2.5000000000000000, and 2. Integer division discards the fraction, and numeric division keeps decimal digits. Casting a double precision value to integer rounds half to even, giving 2, while casting numeric 2.5 rounds half away from zero, giving 3.
Exercise
A table has created_at timestamptz with an index. Rewrite WHERE created_at::date = '2026-03-01' so the index can be used, and name the cast category that lets you insert a numeric value into an integer column.
Show answer
Use WHERE created_at >= '2026-03-01' AND created_at < '2026-03-02', which compares the column directly against constants. Storing numeric in an integer column uses an assignment cast, which PostgreSQL applies automatically during INSERT and UPDATE.