Sub topic 2
CAST, :: and typed literals
This chapter assumes you can write basic SQL (SELECT, WHERE, INSERT, CREATE TABLE) and know the common PostgreSQL types: integer, numeric, text, boolean, date, and timestamp. You also need psql or another PostgreSQL client. By the end you will know the three explicit conversion syntaxes, how they differ in precedence and portability, and which errors each one produces.
Three spellings of one operation
PostgreSQL has three ways to ask for a conversion. All three are explicit: you name the target type, and the server converts the value or raises an error.
SELECT CAST('42' AS integer) AS a,
'42'::integer AS b,
integer '42' AS c;Each column is the integer 42. The table below compares the forms.
| Form | Example | Standard SQL? | Applies to |
|---|---|---|---|
| `CAST(expr AS type)` | `CAST(x AS integer)` | Yes | Any expression |
| `expr::type` | `x::integer` | No, PostgreSQL-specific | Any expression |
| `type 'literal'` | `integer '42'` | Partly (date, time, interval) | Quoted string literals only |
CAST: the portable form
CAST(expression AS type) is defined by the SQL standard, so it works in most databases. Use it in code that must run on more than one system, or when you generate SQL from a tool.
SELECT CAST('2026-11-27' AS date) AS d,
CAST(3.14159 AS numeric(5,2)) AS rounded,
CAST(NULL AS integer) AS typed_null;The type can include a modifier, such as the precision and scale of numeric(5,2). The second column is 3.14. The third column is a NULL that has a known type, which matters when you need the column type of a VALUES list or a UNION branch to be fixed.
The :: operator: the short form
expression::type is shorter and reads left to right, so chained conversions are easy to follow:
SELECT '2026-11-27'::date + 30 AS thirty_days_later,
('{"n": 7}'::jsonb ->> 'n')::int AS n;You can chain it: '42'::text::integer converts the literal to text and then to an integer.
Precedence
:: binds more tightly than almost every operator, including arithmetic and unary minus. It applies only to the item directly to its left. This leads to a common mistake:
SELECT (1 + 2)::text AS ok;
SELECT 1 + 2::text AS fails;The first query returns the text 3. In the second, the cast attaches to 2 only, so PostgreSQL sees integer + text and raises operator does not exist: integer + text. When in doubt, add parentheses around the expression you want to convert.
Casting parameters
In a prepared statement, a cast tells PostgreSQL what type a placeholder has:
PREPARE find_user (integer) AS
SELECT $1::bigint AS id;
EXECUTE find_user(7);Without a type, a bare $1 is resolved from context, and if the context gives no clue the statement fails with could not determine data type of parameter $1. Adding $1::integer removes the ambiguity.
Typed literals
A typed literal puts the type name before a quoted string:
SELECT date '2026-11-27' + 1 AS next_day,
interval '2 hours' AS duration,
boolean 'yes' AS flag,
timestamptz '2026-11-27 10:00:00+00' AS instant;date '2026-11-27' + 1 returns 2026-11-28, because adding an integer to a date adds days. boolean 'yes' is true, since the boolean input function accepts several spellings.
A typed literal is not a general cast:
- It works only on a string literal in single quotes.
integer some_columnis a syntax error, and so isinteger ('4' || '2'). UseCASTor::for those. - The string is passed straight to the type's input function.
integer '42'and'42'::integerdo the same work. - Some type names that are two words, such as
double precision, work, and others do not take a modifier in this position. If a typed literal gives a syntax error, switch to::.
Typed literals are most useful for dates, times, and intervals, where the type name documents the value. They also help when you want to fix a literal's type at the point where it appears, so that it is not left to later resolution rules (the next chapter, on literals, covers this).
What a cast does at run time
A cast does not change the stored value in place. It produces a new value of the target type. For built-in types, PostgreSQL either calls a registered conversion function or, when none exists, converts via text by running the source type's output function and the target type's input function. For example, '42'::integer runs the integer input function on the string 42. The same function is called for 'abc'::integer, which fails:
SELECT 'abc'::integer;
-- ERROR: invalid input syntax for type integer: "abc"The three syntaxes produce the same errors. Whether a conversion exists at all depends on the source and target types, and the later chapters on cast contexts and pg_cast explain how to check.
Type modifiers in casts
Modifiers such as length, precision, and scale are part of the target type, and they change the result:
SELECT 'abcd'::varchar(2) AS truncated,
12.345::numeric(4,1) AS rounded,
'12:34:56.789'::time(0) AS whole_seconds;The results are ab, 12.3, and 12:34:57. An explicit cast to varchar(2) silently truncates, while an INSERT of the same text into a varchar(2) column fails. Casts to a numeric type with too few digits raise numeric field overflow instead of truncating.
Arrays and other composite targets
Array types take brackets after the type name, with either form:
SELECT '{1,2,3}'::int[] AS a,
CAST(ARRAY[1,2,3] AS text[]) AS b;The array-literal string must follow PostgreSQL's array syntax, with braces and commas. The first column is an integer[] and the second a text[].
Choosing a form
- Use
CASTin code that must be portable, and in generated SQL where::may clash with parameter syntax. - Use
::in interactive work and in PostgreSQL-only code, where the short form and left-to-right chaining are easier to read. - Use typed literals for constants, especially
date,timestamp, andintervalvalues. - Use parentheses whenever a cast follows a longer expression.
Whichever form you pick, be consistent within a codebase. The choice affects readability only. The planner treats all three as the same operation.
Exercise
What does each of these statements do, and why? (1) SELECT 10 + 5::text; (2) SELECT (10 + 5)::text; (3) SELECT integer ('4' || '2');
Show answer
(1) It fails with "operator does not exist: integer + text", because :: binds tighter than + and so converts only the 5 to text. (2) It returns the text '15', because the parentheses make the cast apply to the sum. (3) It is a syntax error, because a typed literal accepts only a quoted string literal, not an expression. Write CAST('4' || '2' AS integer) or ('4' || '2')::integer instead, which returns 42.
Exercise
Write one query that returns the date 30 days after 2026-11-27 using a typed literal, and one that returns the integer 7 from the text '7' using the standard-SQL form.
Show answer
SELECT date '2026-11-27' + 30; returns 2026-12-27. SELECT CAST('7' AS integer); returns 7.