Sub topic 1
How PostgreSQL types and conversions fit together
Prerequisites
This chapter assumes you know basic SQL: SELECT, WHERE, INSERT and CREATE TABLE. You should recognize common types such as integer, numeric, text, and date. You need psql or another PostgreSQL client to run the examples.
Every value in PostgreSQL has a type. The type sets what the value can hold and which operators apply to it. A conversion changes a value from one type to another. PostgreSQL performs some conversions automatically and requires you to request others.
CAST, :: and typed literals
You can request a conversion explicitly in three equivalent ways:
SELECT CAST('42' AS integer) AS a,
'42'::integer AS b,
integer '42' AS c;All three return the integer 42. CAST is standard SQL. The :: operator is PostgreSQL-specific and shorter. The typed literal form works only with a literal string.
What type is a literal?
A quoted value such as '2' starts with the unknown type. PostgreSQL resolves it from the surrounding expression:
SELECT 1 + '2' AS ok; -- returns 3
SELECT 1 + '2'::text AS fails; -- ERROR: operator does not exist: integer + textIn the first query, the unknown literal becomes an integer. In the second, the explicit text cast stops that resolution, so no + operator accepts an integer and text.
Converting between numeric types
Casting numeric to integer rounds the value. Parsing text as an integer does not round.
SELECT '3.7'::numeric::integer AS rounded; -- returns 4
SELECT '3.7'::integer AS fails; -- ERROR: invalid input syntax for type integer> The first query is safe for a numeric value. The second fails because the integer input parser rejects a decimal point.
Integer widening, such as integer to bigint, is allowed implicitly. Narrowing, such as integer to smallint, needs an assignment or an explicit cast.
Exercise
Which expression returns 5: '4.6'::numeric::integer or '4.6'::integer?
Show answer
'4.6'::numeric::integer returns 5 because numeric-to-integer casting rounds. '4.6'::integer raises an error because text is parsed with the integer input function, which rejects decimal points.