skip to content

text, varchar and collations

why varchar(255) is a habit from another database, and why 'B' sorts before 'a' here.

address
everything.types.text_and_collation
part
part 6, types and values
chapter
chapter 3 of 11
reading time
8 min

text, varchar(n) and char(n) are stored the same way. varchar(n) adds a length check and nothing else; char(n) pads with spaces and then pretends they aren't there. use text, and a CHECK if the length really matters.

how text compares and sorts is the collation's job. this page's database uses C, byte order, so 'B' < 'a'. a real server can sort like a dictionary, in any language, and compare without caring about case.

the picture

you know how every schema you've inherited has varchar(255) on every column? nobody remembers choosing 255. it's a habit from databases where the declared length decided how a row was stored, or how much of a column an index could hold. in postgres, it decides nothing about storage.

think of three boxes from the same shelf, with different labels. text is the plain box. varchar(5) is the same box with a sticker that says "five at most". char(5) is the box with the empty space stuffed with packing peanuts (spaces) so it always looks full, and a habit of ignoring the peanuts when you compare.

char(5): 6 bytes
hdr
a
b
␠
␠
␠
varchar(5): 3 bytes
hdr
a
b
text: 3 bytes
hdr
a
b
real output, postgres 18.6 (PGlite 0.5.12) · text-and-collation
the letters ab stored in three columns of one row, measured with pg_column_size. each starts with a 1-byte length header. char(5) also stores three spaces of padding: 6 bytes against 3 and 3.

same header, same bytes, same code underneath. the only differences are the rules on the way in.

text, varchar(n), char(n)

varchar(n) refuses a value longer than n characters (characters, not bytes):

sqlempty db
CREATE TABLE users (name varchar(5));
INSERT INTO users (name) VALUES ('Ada Lovelace');
output, from postgres 18.6
#1 · CREATE TABLE
#2 · ERROR 22001
ERROR 22001: value too long for type character varying(5)

but only when you store it. an explicit cast to varchar(n) cuts the string down without a word, because the standard says so:

sqlempty db
SELECT 'Ada Lovelace'::varchar(3) AS cut, 'Ada Lovelace'::text AS whole;
output, from postgres 18.6
SELECT 1
cutvarcharwholetext
AdaAda Lovelace
(1 row)

char(n) (or character(n), or bpchar) pads every value with spaces up to n, and treats trailing spaces as meaningless when it compares. that's the whole difference, and it leaks:

sqlempty db
SELECT 'ab'::char(5) = 'ab   '::char(5)        AS char_equal,
       'ab'::varchar(5) = 'ab   '::varchar(5)  AS varchar_equal,
       length('ab'::char(5))                   AS char_length,
       octet_length('ab'::char(5))             AS char_bytes;
output, from postgres 18.6
SELECT 1
char_equalboolvarchar_equalboolchar_lengthint4char_bytesint4
tf25
(1 row)
predict the output
sql
SELECT 'ab'::char(5) || 'x'       AS glued,
       concat('ab'::char(5), 'x') AS concatenated;
sqlempty db
SELECT 'ab'::char(5) || 'x'       AS glued,
       concat('ab'::char(5), 'x') AS concatenated;
output, from postgres 18.6
SELECT 1
gluedtextconcatenatedtext
abxab x
(1 row)

so: text for strings. if a length limit is a business rule, it's a constraint, and a CHECK says so more honestly than a type: CHECK (length(code) = 2) (more on that in NOT NULL, CHECK and UNIQUE). varchar(n) isn't wrong, just pointless, with one exception: making it wider later is free. postgres keeps the same file, and only narrowing has to rewrite the table and check every row:

sqlempty db
CREATE TABLE people (name varchar(50));
INSERT INTO people VALUES ('Ada Lovelace'), ('Grace Hopper');
SELECT pg_relation_filenode('people') AS file_before;
ALTER TABLE people ALTER COLUMN name TYPE varchar(255);
SELECT pg_relation_filenode('people') AS file_after_widening;
ALTER TABLE people ALTER COLUMN name TYPE varchar(20);
SELECT pg_relation_filenode('people') AS file_after_narrowing;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 2
#3 · SELECT 1
file_beforeoid
16384
(1 row)
#4 · ALTER TABLE
#5 · SELECT 1
file_after_wideningoid
16384
(1 row)
#6 · ALTER TABLE
#7 · SELECT 1
file_after_narrowingoid
16387
(1 row)

same file number after widening, a new one after narrowing: the table was rewritten. (the files behind a table explains the file number.)

collation: who decided 'B' < 'a'

comparing two strings means deciding an order for every pair of characters, and that's what a collation is: a set of rules for <, = and ORDER BY. this page's database was created with the C collation:

sqlempty db
SELECT datcollate, datctype FROM pg_database WHERE datname = current_database();
SELECT 'B' < 'a' AS capital_b_first, 'Zoe' < 'Zoë' AS plain_e_first;
output, from postgres 18.6
#1 · SELECT 1
datcollatetextdatctypetext
CC.UTF-8
(1 row)
#2 · SELECT 1
capital_b_firstboolplain_e_firstbool
tt
(1 row)

C compares bytes. capital letters are 41 to 5a in UTF-8, small ones 61 to 7a, and anything accented starts with a byte above all of them. so Banana and Zoë come before apple, and Ångström and Öl come after zebra:

sqlempty db
SELECT w
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('ost'), ('Öl'), ('zebra'), ('zoe'), ('Zoë'), ('Ångström')) AS t (w)
ORDER BY w;
output, from postgres 18.6
SELECT 9
wtext
Banana
Zoë
apple
cherry
ost
zebra
zoe
Ångström
Öl
(9 rows)

a real server can use ICU, the unicode consortium's collation library, which knows how dozens of languages sort. and they don't agree:

COLLATE =
sort.sql
  1. 1SELECT w FROM words ORDER BY w COLLATE "C";
the result for C
wtext
Banana
Zoë
apple
cherry
ost
zebra
zoe
Ångström
Öl
(9 rows)

C: byte order. every capital before every small letter, and anything accented after z.

real output, a postgres 18.6 server · collations
the same nine words sorted under three collations, on a postgres 18.6 server. C is byte order. english sorts by letter first, then accent, then case. swedish has Å and Ö as letters of their own, after z.

none of these is wrong. Ångström is next to apple for an english speaker and at the end of the dictionary for a swede. the database can't know which you want, so you say it, at one of three levels: the database's default (CREATE DATABASE ... LOCALE), a column (name text COLLATE "sv-SE-x-icu"), or one expression (ORDER BY name COLLATE "sv-SE-x-icu").

the browser's engine has ICU's language-neutral root order and nothing more (it answers to unicode and to und-x-icu). for these nine words it agrees with english, letters first and case last:

sqlempty db
SELECT w
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('ost'), ('Öl'), ('zebra'), ('zoe'), ('Zoë'), ('Ångström')) AS t (w)
ORDER BY w COLLATE "unicode";
output, from postgres 18.6
SELECT 9
wtext
Ångström
apple
Banana
cherry
Öl
ost
zebra
zoe
Zoë
(9 rows)

ICU can do things byte order never could. a custom collation with kn (numeric) sorts digits by their value, so item 9 comes before item 10:

sqlempty db
CREATE COLLATION numeric_sort (provider = icu, locale = 'en-u-kn');
SELECT x
FROM (VALUES ('item 10'), ('item 9'), ('item 100'), ('Item 2')) AS t (x)
ORDER BY x COLLATE numeric_sort;
output, from a real postgres 18.6 server
#1 · CREATE COLLATION
#2 · SELECT 4
xtext
Item 2
item 9
item 10
item 100
(4 rows)

checked on a real postgres 18.6 server. the browser engine can't run this one.

comparing without case

the browser can do the simple version. lower() on both sides, or ILIKE, which postgres has and the standard doesn't postgres only:

sqlempty db
SELECT lower('Zoë') = lower('ZOË') AS lowered, 'Zoë Martin' ILIKE 'zoë%' AS ilike;
output, from postgres 18.6
SELECT 1
loweredboolilikebool
tt
(1 row)

both true here. but there are more ways, and they disagree in the corners. on a server:

methodzoe, ZOEZoë, ZOËzoe, Zoë
a = bfff
lower(a) = lower(b)tff
citexttff
COLLATE cittf
COLLATE ai_cittt
(5 rows)
real output, a postgres 18.6 server · collations
three pairs of strings, five ways to compare them, on a postgres 18.6 server whose ctype is C. t means equal. lower() and citext only fold what the database's ctype knows, which on this server is plain ASCII. the ICU collations know unicode.
  • lower() on both sides works anywhere, but an index on email won't serve lower(email) = .... index the expression: CREATE INDEX ON users (lower(email)) (expression indexes).
  • citext is an extension with a case-insensitive text type. it calls lower() for you on every comparison, so it folds exactly what lower() does under the database's ctype. the browser can't load it.
  • a nondeterministic collation decides equality by ICU's rules instead of bytes. ks-level2 ignores case, ks-level1 ignores accents too. this is the modern answer, and the only one that knows unicode on every server.

a nondeterministic collation on a column changes what UNIQUE means:

sqlempty db
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
CREATE TABLE members (name text COLLATE ci UNIQUE);
INSERT INTO members VALUES ('Zoë');
INSERT INTO members VALUES ('ZOË');
output, from a real postgres 18.6 server
#1 · CREATE COLLATION
#2 · CREATE TABLE
#3 · INSERT 0 1
#4 · ERROR 23505
ERROR 23505: duplicate key value violates unique constraint "members_name_key"
DETAIL: Key (name)=(ZOË) already exists.

checked on a real postgres 18.6 server. the browser engine can't run this one.

since postgres 18 pg 18+, LIKE works with nondeterministic collations too (it used to be an error):

sqlempty db
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
SELECT 'Zoë Martin' LIKE 'ZOË%' COLLATE ci AS case_blind_like;
output, from a real postgres 18.6 server
#1 · CREATE COLLATION
#2 · SELECT 1
case_blind_likebool
t
(1 row)

checked on a real postgres 18.6 server. the browser engine can't run this one.

keylines

  • text, varchar(n) and char(n) are stored the same way; only the rules on the way in differ.
  • varchar(n) checks a length, char(n) pads with spaces. prefer text, with a CHECK if needed.
  • a collation decides order and equality. the browser's is C: byte order, so 'B' < 'a'.
  • languages sort differently, and ICU collations on a server know how.
  • for case-insensitive matching: lower() plus an expression index, citext, or a nondeterministic collation.