Sub topic 6
Implicit, assignment and explicit casts
This chapter assumes you can write basic SQL, know the common PostgreSQL types, and have psql or another client open. It explains the three contexts that decide whether PostgreSQL converts a value for you or makes you ask for the conversion.
Three contexts, one rule
Every cast that PostgreSQL knows about carries a context. The context says where the server may apply the conversion without being told.
| Context | Applied automatically where | `castcontext` in `pg_cast` |
|---|---|---|
| Implicit | Anywhere: expressions, function arguments, assignments | `i` |
| Assignment | Only when storing a value into a column (`INSERT`, `UPDATE`) | `a` |
| Explicit | Only when you write `CAST(...)`, `::` or a typed literal | `e` |
The contexts nest. An implicit cast is also allowed on assignment and explicitly. An assignment cast is also allowed explicitly. An explicit-only cast never runs unless you ask for it.
The design goal is safety. Widening conversions that cannot lose information, such as integer to bigint, are implicit. Conversions that can lose information, such as integer to smallint, require you to be storing the value or to say so yourself.
Reading the contexts from pg_cast
The pg_cast catalog stores each cast and its context. This query compares a widening cast with a narrowing one.
SELECT castsource::regtype, casttarget::regtype, castcontext
FROM pg_cast
WHERE castsource = 'int4'::regtype
AND casttarget IN ('int8'::regtype, 'int2'::regtype);The integer to bigint row has castcontext i. The integer to smallint row has a. The catalog also has a castmethod column. It is f when a function does the work, b when the types are binary-coercible (no work at all), and i for I/O conversion, which is covered below.
Implicit casts in action
Because smallint to integer is implicit, mixing the two in an expression just works. The same holds for integer to numeric.
SELECT 1::smallint + 1::integer AS widened,
1 + 2.5 AS to_numeric;The first column is 2 and the second is 3.5. In both cases PostgreSQL picked the wider type for you. Implicit casts also apply when you call a function. A function that accepts bigint accepts an integer argument without complaint.
Assignment casts: only when storing
Assignment casts fire when PostgreSQL stores a value into a column. Here is a small table that shows the difference.
CREATE TABLE cast_demo (
small_n smallint,
whole_n integer,
label text
);
INSERT INTO cast_demo VALUES (100, 3.7, 12345);
SELECT * FROM cast_demo;The row stored is 100, 4, 12345. Three assignment casts ran:
- The integer literal
100went into asmallintcolumn (integertosmallint). - The numeric value
3.7went into anintegercolumn (numerictointeger), which rounds. - The integer
12345went into atextcolumn.
An assignment cast still checks the value. Inserting 70000 into small_n fails with smallint out of range, because the conversion function raises an error when the value does not fit.
The same casts are not available inside an expression or function call. The next query fails.
SELECT repeat('ab', 2.0);repeat takes an integer as its second argument. The literal 2.0 is numeric, and numeric to integer is only an assignment cast. PostgreSQL does not consider it when looking for a matching function, so you get a function ... does not exist error. Write repeat('ab', 2) or repeat('ab', 2.0::integer) instead.
Explicit-only casts
Some conversions are never applied unless you ask. The most important group is conversion from text to other types. This is why you cannot silently treat a string column as a number.
SELECT '42'::text::integer AS ok;
SELECT length(12345) AS fails;The first query works because you wrote the cast. The second fails because length accepts text, and integer to text is not implicit. The failure is useful, because it points at a likely bug rather than guessing.
I/O conversion casts and the string rule
Many pairs of types have no row in pg_cast. For those, PostgreSQL can fall back on an I/O conversion cast. It writes the value out as text with the source type's output function, then reads that text with the target type's input function. The context of these automatic casts follows a fixed rule:
- Conversion to a string type (
text,varchar,char) is allowed in assignment context. - Conversion from a string type is allowed only explicitly.
This explains the INSERT of 12345 into a text column above, and the failure of length(12345). Because the conversion goes through the type's input function, its error messages come from that function. For example, '3.7'::integer fails with invalid input syntax for type integer, while '3.7'::numeric::integer succeeds and rounds to 4.
Same cast, different behavior by context
A few casts behave differently depending on whether you invoke them explicitly or on assignment. The clearest case is length-limited character types.
SELECT 'abcd'::varchar(2) AS explicit_cast;
CREATE TABLE short_text (v varchar(2));
INSERT INTO short_text VALUES ('abcd');The explicit cast silently truncates and returns ab. The INSERT fails with value too long for type character varying(2). The SQL standard requires this split. An explicit cast means "I know what I am asking for," while storing into a column must not lose data without notice.
Why implicit casts are kept few
It is tempting to make every cast implicit, but implicit casts widen the set of candidates the server considers when resolving operators and functions. More implicit casts means more chances that an expression silently means something you did not intend, or becomes ambiguous. Older PostgreSQL releases allowed most types to convert to text implicitly, and that hid bugs such as comparing a number to a string. Those casts were tightened to assignment-only.
The practical consequences for your own code:
- Treat an error like
operator does not exist: integer = textas a sign that two columns have different types, not as something to fix by sprinkling casts everywhere. - When you create a custom cast later, prefer explicit or assignment context. Mark a cast
AS IMPLICITonly when it is lossless and unambiguous. - Do not rely on assignment-context behavior to do rounding you care about. Cast explicitly, or call
round(), so the intent is visible in the query.
Quick reference
- Widening, lossless conversions are implicit.
- Narrowing conversions, such as
integertosmallintornumerictointeger, are assignment casts. They work when storing and fail in function calls. - Conversions from text are explicit only.
- Conversions to text are assignment casts.
- Check
pg_cast.castcontextwhen you are unsure.
Exercise
Given a table with an integer column qty, INSERT INTO t (qty) VALUES (2.6) stores 3, but SELECT repeat('x', 2.6) raises an error. Explain both results using cast contexts.
Show answer
The insert applies the numeric to integer cast in assignment context, which is allowed when storing into a column, and it rounds 2.6 to 3. The repeat call needs an integer argument and passes through function resolution, which only considers implicit casts. Numeric to integer is an assignment cast, so no matching function is found and PostgreSQL reports that the function does not exist.
Exercise
Why does SELECT 'abcd'::varchar(2) return ab while INSERT INTO short_text VALUES ('abcd') into a varchar(2) column fails?
Show answer
The explicit cast is a request to convert and truncate, so PostgreSQL truncates silently. An insert uses the assignment path, where the length check raises value too long for type character varying(2) instead of discarding data.