Sub topic 5
Converting to and from text, varchar and char
This chapter assumes you know the CAST and :: syntax and the difference between explicit, assignment and implicit casts, which earlier chapters cover. It focuses on the three character types and on how PostgreSQL moves values into and out of them.
The three character types
PostgreSQL has three main character types. They differ in how they treat length and trailing spaces.
| Type | Length limit | Padding | Behavior to remember |
|---|---|---|---|
| `text` | None | None | Keeps every character, including trailing spaces |
| `varchar(n)` | `n` characters | None | Rejects longer values on insert. An explicit cast truncates |
| `char(n)` | `n` characters | Pads with spaces to `n` | Trailing spaces are ignored in comparisons and `length` |
varchar with no length behaves like text. Limits count characters, not bytes. char with no length means char(1).
Internally, char(n) is called bpchar ("blank-padded char"). You will see that name in error messages and in pg_cast. Do not confuse it with "char", written with double quotes. That is a separate one-byte internal type, not a character string type.
Explicit casts truncate, assignments fail
When you cast explicitly to a length-limited type, PostgreSQL silently cuts the value. When you store a value into a column, it raises an error instead.
SELECT 'abcd'::varchar(2) AS v,
'abcd'::char(2) AS c,
'abc'::char AS bare_char;This returns ab, ab and a. The bare char is char(1), which surprises many people.
CREATE TABLE short_text (v varchar(2));
INSERT INTO short_text VALUES ('ab '); -- succeeds: excess characters are only spaces
INSERT INTO short_text VALUES ('abcd'); -- ERROR: value too long for type character varying(2)The SQL standard requires this split. Truncation on an explicit cast is a deliberate request. An insert that loses data is probably a bug, so it fails. The one exception is excess characters that are all spaces, which are dropped without error.
How char(n) padding behaves
Padding is stored, but PostgreSQL mostly hides it:
SELECT length('ab'::char(5)) AS len,
octet_length('ab'::char(5)) AS bytes,
'ab'::char(5)::text || '|' AS as_text,
'a'::char(3) = 'a '::char(3) AS char_equal,
'a'::text = 'a '::text AS text_equal;The results are len = 2, bytes = 5, as_text = ab|, char_equal = true and text_equal = false. Three rules follow from this:
lengthignores the padding, butoctet_lengthcounts it.- Casting
char(n)totextorvarcharremoves trailing spaces. - Comparing two
charvalues ignores trailing spaces. Comparing twotextvalues does not.
Any type to text
Every type has an output function, which produces its text form. PostgreSQL uses it to build an automatic conversion, called an I/O conversion cast. Converting to a string type is allowed on assignment, so you can store a number in a text column without writing a cast.
SELECT 42::text AS int_text,
true::text AS bool_text,
DATE '2026-11-27'::text AS date_text,
ARRAY[1,2,3]::text AS array_text,
'id=' || 5 AS concat_number;You get 42, true, 2026-11-27, {1,2,3} and id=5. The date text depends on the DateStyle setting. Do not rely on the default format in application code. Use to_char, covered in a later chapter, when the output format matters.
CREATE TABLE labels (code varchar(5), note text);
INSERT INTO labels VALUES (12345, 'ok'); -- integer stored as '12345' (assignment cast)
INSERT INTO labels VALUES (123456, 'too long');
-- ERROR: value too long for type character varying(5)The || operator accepts a text value on one side and any non-array value on the other, so 'id=' || 5 works. Two non-text values do not. SELECT 1 || 2 fails with operator does not exist: integer || integer. Cast one side, for example 1::text || 2.
Text to any type
The reverse direction runs the target type's input function on the string. These I/O casts from string types are explicit only, so PostgreSQL will not apply them for you on assignment.
CREATE TABLE nums (n integer);
INSERT INTO nums VALUES ('7'); -- works: '7' is an untyped literal
INSERT INTO nums VALUES ('7'::text); -- ERROR: column "n" is of type integer
-- but expression is of type text
INSERT INTO nums VALUES ('7'::text::integer); -- worksThe first insert works because an untyped literal is not yet text. It is resolved directly as an integer, as the earlier chapter on literals explained. A value that already has the type text, such as a column or a function result, needs an explicit cast.
Input functions have their own parsing rules:
SELECT ' 42 '::integer AS padded,
'yes'::boolean AS flag,
'1e3'::numeric AS sci;This returns 42, true and 1000. Input functions trim surrounding whitespace for numbers and booleans. The boolean parser accepts t, true, yes, on and 1, and their opposites, in any case. The same text can still fail on another type. '1e3'::integer raises invalid input syntax for type integer, because the integer parser does not accept exponents.
Conversions between character types
Converting text to varchar(n) follows the explicit-versus-assignment rule above. Converting varchar to text never loses data. Converting char(n) to anything else strips trailing spaces first. If you need a fixed-width string with spaces preserved, use rpad, which returns text:
SELECT rpad('ab', 5) || '|' AS padded_text;The result is ab |. The padding survives because the value is text, not char.
Common errors
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `value too long for type character varying(n)` | Insert or update of a longer string | Validate input, widen the column, or cast explicitly if truncation is intended | ||
| `invalid input syntax for type integer: "3.7"` | The text is not valid input for the target type | Cast through `numeric` first, or check with `pg_input_is_valid` | ||
| `column ... is of type integer but expression is of type text` | Assigning a typed `text` value to a non-text column | Add an explicit cast | ||
| `operator does not exist: integer \ | \ | integer` | Concatenating two non-text values | Cast one operand to `text` |
| `'abc'::char` returns `a` | `char` means `char(1)` | Give an explicit length, or use `text` | ||
| Concatenation returns NULL | ` | ` with a NULL operand yields NULL | Use `concat()`, which treats NULL as an empty string |
SELECT ('a' || NULL) IS NULL AS operator_null,
concat('a', NULL, 'b') AS concat_result;This returns true and ab.
Exercise
A table has a column code char(6). You run SELECT code::text || '|' FROM t on a row that holds 'AB'. What does the query return, and what is octet_length(code) for that row?
Show answer
The query returns AB|, because converting char(n) to text removes the trailing padding. octet_length(code) returns 6, because the stored value is padded to six characters and octet_length counts the padding.
Exercise
Which of these statements raises an error, and why? (a) SELECT 'hello'::varchar(3); (b) INSERT INTO short_text VALUES ('hello'); where short_text(v varchar(3)).
Show answer
Only (b) fails, with value too long for type character varying(3). The explicit cast in (a) silently truncates the value to hel. An assignment into a column is not allowed to lose non-space characters.