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.
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):
CREATE TABLE users (name varchar(5));
INSERT INTO users (name) VALUES ('Ada Lovelace');but only when you store it. an explicit cast to varchar(n) cuts the string down without a word, because the standard says so:
SELECT 'Ada Lovelace'::varchar(3) AS cut, 'Ada Lovelace'::text AS whole;| cutvarchar | wholetext |
|---|---|
| Ada | Ada Lovelace |
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:
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;| char_equalbool | varchar_equalbool | char_lengthint4 | char_bytesint4 |
|---|---|---|---|
| t | f | 2 | 5 |
SELECT 'ab'::char(5) || 'x' AS glued,
concat('ab'::char(5), 'x') AS concatenated;SELECT 'ab'::char(5) || 'x' AS glued,
concat('ab'::char(5), 'x') AS concatenated;| gluedtext | concatenatedtext |
|---|---|
| abx | ab x |
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:
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;| file_beforeoid |
|---|
| 16384 |
| file_after_wideningoid |
|---|
| 16384 |
| file_after_narrowingoid |
|---|
| 16387 |
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:
SELECT datcollate, datctype FROM pg_database WHERE datname = current_database();
SELECT 'B' < 'a' AS capital_b_first, 'Zoe' < 'Zoë' AS plain_e_first;| datcollatetext | datctypetext |
|---|---|
| C | C.UTF-8 |
| capital_b_firstbool | plain_e_firstbool |
|---|---|
| t | t |
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:
SELECT w
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('ost'), ('Öl'), ('zebra'), ('zoe'), ('Zoë'), ('Ångström')) AS t (w)
ORDER BY w;| wtext |
|---|
| Banana |
| Zoë |
| apple |
| cherry |
| ost |
| zebra |
| zoe |
| Ångström |
| Öl |
a real server can use ICU, the unicode consortium's collation library, which knows how dozens of languages sort. and they don't agree:
- 1SELECT w FROM words ORDER BY w COLLATE "C";
| wtext |
|---|
| Banana |
| Zoë |
| apple |
| cherry |
| ost |
| zebra |
| zoe |
| Ångström |
| Öl |
C: byte order. every capital before every small letter, and anything accented 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:
SELECT w
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('ost'), ('Öl'), ('zebra'), ('zoe'), ('Zoë'), ('Ångström')) AS t (w)
ORDER BY w COLLATE "unicode";| wtext |
|---|
| Ångström |
| apple |
| Banana |
| cherry |
| Öl |
| ost |
| zebra |
| zoe |
| Zoë |
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:
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;| xtext |
|---|
| Item 2 |
| item 9 |
| item 10 |
| item 100 |
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:
SELECT lower('Zoë') = lower('ZOË') AS lowered, 'Zoë Martin' ILIKE 'zoë%' AS ilike;| loweredbool | ilikebool |
|---|---|
| t | t |
both true here. but there are more ways, and they disagree in the corners. on a server:
| method | zoe, ZOE | Zoë, ZOË | zoe, Zoë |
|---|---|---|---|
| a = b | f | f | f |
| lower(a) = lower(b) | t | f | f |
| citext | t | f | f |
| COLLATE ci | t | t | f |
| COLLATE ai_ci | t | t | t |
- lower() on both sides works anywhere, but an index on
emailwon't servelower(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-level2ignores case,ks-level1ignores 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:
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Ë');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):
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
SELECT 'Zoë Martin' LIKE 'ZOË%' COLLATE ci AS case_blind_like;| case_blind_likebool |
|---|
| t |
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.