Sub topic 1
Character types: text, varchar and char(n)
PostgreSQL has three everyday character types: text, varchar(n) and char(n). They look similar, but they differ in length checks, padding and comparison rules. This chapter explains those differences so you can pick a type for each column and predict what string functions return.
Prerequisites
This chapter assumes you can:
- Write basic
SELECT,WHEREandGROUP BYqueries. - Recognize PostgreSQL data types and know that
NULLmeans "unknown or missing". - Run queries in
psqlor another SQL client.
Every later chapter in this tutorial builds on the type behavior described here.
The three types at a glance
| Type | Aliases | Length rule | Padding |
|---|---|---|---|
| `text` | none | Any length, up to about 1 GB | None |
| `varchar(n)` | `character varying(n)` | At most `n` characters | None |
| `varchar` | `character varying` | Same as `text` | None |
| `char(n)` | `character(n)`, `bpchar` | Exactly `n` characters | Padded with spaces to `n` |
Some points apply to all of them:
- The limit
ncounts characters, not bytes. In a UTF8 database,varchar(5)can hold five accented letters even though they take more than five bytes. textis PostgreSQL's own type and is not in the SQL standard.varchar(n)andchar(n)are standard.charwith no length meanschar(1).varcharwith no length means unlimited. Do not confuse them.- The largest
nyou can declare is 10,485,760. Values with no declared limit can still reach about 1 GB.
text and varchar share the same storage
Internally, text and varchar use the same storage format. PostgreSQL stores short values with a 1-byte header and longer values with a 4-byte header. It compresses and moves very large values out of line with a mechanism called TOAST. None of this depends on whether you declared a limit.
Because of this, a limit is not a performance feature. A varchar(255) column is not faster or smaller than a text column holding the same data. The only difference is that PostgreSQL checks the length when a row is written.
You can confirm which type an expression has with pg_typeof:
SELECT pg_typeof('hello'::text) AS t,
pg_typeof('hello'::varchar(10)) AS v,
pg_typeof('hello'::char(10)) AS c;This returns text, character varying and character.
How varchar(n) enforces its limit
When you insert a value longer than n, PostgreSQL raises an error. There is one exception: if the extra characters are all spaces, PostgreSQL silently trims them.
CREATE TABLE limit_demo (code varchar(3));
INSERT INTO limit_demo VALUES ('abc'); -- ok
INSERT INTO limit_demo VALUES ('abc '); -- ok, trailing spaces trimmed to 'abc'
INSERT INTO limit_demo VALUES ('abcd'); -- ERROR: value too long for type character varying(3)An explicit cast behaves differently. Casting a long string to varchar(n) truncates it without an error:
SELECT 'abcdef'::varchar(3) AS cast_style,
CAST('abcdef' AS varchar(3)) AS cast_function;Both columns return abc. This is standard SQL behavior, and it can hide data loss. If a query casts user input to varchar(n), a too-long value is cut off and nobody is told.
Changing the limit later
Changing a limit has different costs depending on direction:
- Raising the limit, or removing it with
ALTER COLUMN ... TYPE text, does not rewrite the table. - Lowering the limit requires PostgreSQL to check every existing row, which takes a lock while it scans.
This is a practical reason to avoid guessing a limit up front. Business rules such as "country codes are 2 letters" are stable. Rules such as "a name is at most 50 characters" often change.
char(n) pads with spaces
A char(n) value is always stored with n characters. Shorter values are padded on the right with spaces. PostgreSQL then treats those trailing spaces as insignificant in most operations.
SELECT length('ab'::char(5)) AS chars,
octet_length('ab'::char(5)) AS bytes,
'ab'::char(5) = 'ab'::char(2) AS equal,
'ab'::char(5)::text || '|' AS as_text;The results are:
charsis 2, becauselengthignores trailing spaces forchar(n).bytesis 5, becauseoctet_lengthcounts the padded storage.equalistrue, because comparison ignores trailing spaces.as_textisab|, because casting totextremoves the padding.
Now compare this with text, where trailing spaces count:
SELECT 'ab '::text = 'ab'::text AS text_equal,
'ab '::varchar(5) = 'ab'::varchar(5) AS varchar_equal,
'ab '::char(5) = 'ab'::char(5) AS char_equal;This returns false, false and true. The same visible data compares differently depending on the type.
Why char(n) rarely helps
Despite what older database books say, char(n) has no speed advantage in PostgreSQL. It usually uses more storage because of the padding, and it adds a cast step in some operations. The padding also surprises people. For example, LIKE does not ignore the padding on a char(n) column, so code LIKE 'ab' can fail to match a padded 'ab ' value.
Use char(n) only when a value is truly fixed width and you want that enforced, or when you must match a legacy schema. Even then, a text column with a check constraint is usually easier to work with.
Choosing a type
The PostgreSQL documentation recommends text or varchar over char(n), and most teams default to text. If a column needs a hard rule, state it as a constraint. A constraint is visible in the schema, can be changed without altering the type, and can express more than a maximum:
CREATE TABLE countries (
iso_code text NOT NULL,
name text NOT NULL,
CONSTRAINT iso_code_shape CHECK (iso_code ~ '^[A-Z]{2}$'),
CONSTRAINT name_length CHECK (char_length(name) BETWEEN 1 AND 100)
);The ~ operator is a regular expression match, covered in a later chapter. Here it requires exactly two uppercase letters. The second constraint uses char_length, which counts characters.
The diagram below summarizes a reasonable decision path.
Common errors and gotchas
- Assuming
varchar(n)counts bytes. It counts characters. If you need a byte limit, useCHECK (octet_length(col) <= n). - Expecting trailing spaces to matter in
char(n). They are ignored in comparison andlength, butoctet_lengthstill counts them. - Mixing types in comparisons. Comparing a
char(n)to atextvalue casts thechar(n)totextfirst, which strips its padding. Results can differ from comparing twochar(n)values. - Silent truncation from casts.
value::varchar(n)shortens long input. AnINSERTof the same value fails. Use the insert path when you want errors. - Choosing a small limit "to be safe". A limit that is too low causes failed inserts in production. A limit that is too high protects nothing.
- Treating the empty string as
NULL. PostgreSQL keeps them distinct.'' IS NULLisfalse. This matters in every concatenation, as the next chapter shows.
Two other character types you may see
PostgreSQL also has name, a 63-byte type used in system catalogs for identifiers such as table names, and "char" (with the double quotes), a single-byte internal type. You rarely need either in application tables. Avoid "char" because it is easy to mistake for char(1).
Exercise
A table has a column sku char(8). A row holds the value 'AB12'. What do length(sku), octet_length(sku) and sku = 'AB12' return, and what is the main reason to change the column to text?
Show answer
length(sku) returns 4, because trailing padding is ignored. octet_length(sku) returns 8, because the stored value is padded to 8 characters (all single-byte). sku = 'AB12' returns true, because the comparison ignores trailing spaces. The main reason to switch to text is that char(n) gives no speed or storage benefit in PostgreSQL and its padding causes surprises, for example with LIKE and concatenation. If SKUs must be exactly 8 characters, a CHECK (char_length(sku) = 8) constraint on a text column states that rule explicitly.