Sub topic 3
What Type Is a Literal?
This chapter assumes basic SELECT queries and familiarity with PostgreSQL types such as integer, numeric, text, date, and timestamp. The focus is how PostgreSQL assigns types to values written directly in a query.
A literal is a value written in SQL rather than read from a table or parameter. For example, 42, '42', DATE '2026-11-27', and NULL are all literals. PostgreSQL assigns each literal a type before it evaluates the surrounding expression.
Numeric and quoted literals
An unquoted number usually receives a numeric type immediately:
SELECT pg_typeof(42) AS whole_number,
pg_typeof(3.14) AS decimal_number,
pg_typeof('42') AS quoted_value;The result is typically integer, numeric, and unknown. A quoted string literal starts with the special unknown type. This does not mean the value is invalid or permanently typeless. It means PostgreSQL will choose a type from context.
For example, the untyped string can work with integer addition:
SELECT 1 + '2' AS result;PostgreSQL resolves '2' as an integer because that is the type required by the selected + operator. An explicitly typed text value is different:
SELECT 1 + '2'::text AS result;This fails because PostgreSQL does not automatically convert text to integer for this operator.
Typed literals
SQL also provides typed-literal syntax. The type name comes before the quoted value:
SELECT DATE '2026-11-27' AS event_date,
TIMESTAMP '2026-11-27 10:30:00' AS event_time,
INTEGER '42' AS event_id;Typed literals are explicit and readable. They also avoid relying on the type inferred from a comparison or function call. The equivalent cast syntax is often more convenient when the value is an expression:
SELECT CAST('42' AS integer) AS standard_sql,
'42'::integer AS postgres_sql;The :: form is PostgreSQL-specific. CAST follows standard SQL.
Context and operator resolution
PostgreSQL uses the surrounding expression to resolve unknown literals. It considers available operators and functions, preferred types, and categories such as numeric or string types.
A literal can therefore behave differently in different contexts:
SELECT pg_typeof('42'::integer) AS explicit_type,
pg_typeof('42') AS unresolved_type;NULL also begins without a concrete type. In an assignment, comparison, function call, or UNION, PostgreSQL uses nearby typed expressions to determine what NULL means.
Exercise
Why does 1 + '2' work while 1 + '2'::text fails?
Show answer
The first quoted value is unknown, so PostgreSQL can resolve it as integer for the addition operator. The second value is explicitly text, and PostgreSQL has no matching integer-plus-text operator.