Sub topic 2
Converting to and from text, varchar and char
This chapter assumes you know SELECT, WHERE and CREATE TABLE, and that you can run queries in psql.
Text, varchar and char
PostgreSQL has three character types. text has no length limit. varchar(n) holds up to n characters. char(n) pads shorter values with spaces to n characters. An explicit cast to a shorter length cuts the value silently, but an INSERT into a column of that length raises an error.
SELECT 'abcd'::varchar(2) AS explicit_cast; -- returns 'ab'
CREATE TABLE short_text (v varchar(2));
INSERT INTO short_text VALUES ('abcd'); -- ERROR: value too longImplicit, assignment and explicit casts
PostgreSQL decides when it converts a value for you. An implicit cast happens with no request, such as integer to bigint. An assignment cast happens when a value is stored in a column, such as integer to smallint. An explicit cast needs CAST or ::, such as text to integer. The castcontext column in pg_cast records which rule applies.
How operators and functions pick argument types
An untyped literal such as '2' has the type unknown. PostgreSQL resolves it to the type of the other operand.
SELECT 1 + '2' AS ok; -- returns 3
SELECT 1 + '2'::text AS fails; -- ERROR: operator does not exist: integer + textto_char, to_number, to_date and to_timestamp
A plain cast cannot parse a custom layout. The formatting functions handle these cases.
SELECT to_char(1234.5, 'FM999,999.00') AS formatted,
to_number('1,234.50', '9,999.99') AS parsed_number,
to_date('27/11/2026', 'DD/MM/YYYY') AS parsed_date;FM removes the padding spaces, so formatted returns 1,234.50.
Dates, timestamps and time zones
Casting a timestamp to a timestamptz reads the value in the session's TimeZone setting. The same text can therefore name different instants in different sessions.
SET TIME ZONE 'UTC';
SELECT '2026-11-27 10:00:00'::timestamp::timestamptz AS as_utc;
SET TIME ZONE 'America/New_York';
SELECT '2026-11-27 10:00:00'::timestamp::timestamptz AS as_new_york;Exercise
Which statement fails, and why? SELECT 1 + '2'::text;
Show answer
It fails with "operator does not exist: integer + text". The cast makes the literal a text value, and PostgreSQL has no operator that adds an integer to text.