Sub topic 2
CAST, `::` and typed literals
This chapter assumes you know SELECT, WHERE, INSERT, and CREATE TABLE, and that you have used PostgreSQL types such as integer, numeric, text, date, and timestamp.
PostgreSQL stores every value with a data type. A cast is an instruction to convert a value from one type to another. For example, text containing digits can become an integer.
Three ways to request a cast
PostgreSQL supports the standard CAST syntax, the PostgreSQL-specific :: operator, and typed literals.
| Form | Example | Main use |
|---|---|---|
| `CAST` | `CAST('42' AS integer)` | Portable SQL |
| `::` | `'42'::integer` | Short PostgreSQL syntax |
| Typed literal | `integer '42'` | Give a literal a type directly |
These three expressions produce the same integer:
SELECT CAST('42' AS integer) AS standard_form,
'42'::integer AS postgres_form,
integer '42' AS typed_literal;CAST is often clearest in shared SQL code. The :: form is common in PostgreSQL queries, especially when casting columns or expressions. A typed literal puts the type before the literal. It is particularly readable for date and timestamp values:
SELECT DATE '2026-11-27' AS report_date,
TIMESTAMP '2026-11-27 10:30:00' AS report_time;Parenthesize an expression before using :: when the expression contains operators:
SELECT (price * quantity)::numeric(12, 2) AS total
FROM order_lines;How quoted literals get a type
A quoted string such as '42' starts with the special unknown type. PostgreSQL delays choosing its final type until it examines the surrounding expression.
flowchart TD
A["'42' quoted literal"] --> B["unknown type"]
B --> C{"Context supplies a type?"}
C -->|yes| D["Convert to the required type"]
C -->|no| E["Resolve using PostgreSQL defaults"]
D --> F["Evaluate expression"]
E --> FFor example, PostgreSQL can resolve '2' as an integer because the other operand is an integer:
SELECT 1 + '2' AS result;The result is 3. However, an explicit cast changes the situation:
SELECT 1 + '2'::text AS result;This fails because PostgreSQL does not have an integer-plus-text operator. Once you cast the literal to text, the server does not silently change it back to integer for this operator.
A cast also documents your intent and catches bad input at the point of conversion:
SELECT CAST('42' AS integer) AS item_count;If the value is not valid integer input, the query raises an error instead of returning a misleading result.
Choosing a syntax
Use CAST when portability and explicit wording matter. Use :: for concise PostgreSQL-specific SQL. Use typed literals for values whose type is part of their meaning, such as DATE '2026-11-27'.
Exercise
What is the difference between SELECT 1 + '2' and SELECT 1 + '2'::text?
Show answer
The first lets PostgreSQL resolve the unknown literal as an integer. The second explicitly makes the literal text, so no integer-plus-text operator matches.