Sub topic 5
Text, varchar and char
This chapter assumes you can write basic SQL (SELECT, INSERT, CREATE TABLE), run queries in psql or another client, and know what a column and a constraint are. It covers the three character types in PostgreSQL, how they differ, and the mistakes people commonly make with them.
The three character types
PostgreSQL has three main types for storing strings:
| Type | Meaning | Length limit | Padding |
|---|---|---|---|
| `text` | Variable-length string | None (up to about 1 GB) | None |
| `varchar(n)` | Variable-length string | At most `n` characters | None |
| `char(n)` | Fixed-length string | Exactly `n` characters | Padded with spaces |
varchar without a length (varchar alone) behaves like text. character varying is the standard SQL name for varchar, and character is the standard name for char. They are interchangeable in DDL.
The limit n counts characters, not bytes. In a UTF-8 database, varchar(5) can hold five characters even if some of them take several bytes each.
text is the default choice
text is not part of the SQL standard, but it is a first-class type in PostgreSQL. It has no length limit and performs the same as the other two types. The PostgreSQL documentation states that there is no performance advantage to char(n) or varchar(n) over text. The only difference is the extra check on length.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
email text NOT NULL
);Long values are stored out of line automatically. PostgreSQL compresses and moves large values into a side table called TOAST storage. You do not need to pick a different type for long text.
varchar(n) enforces a length
Use varchar(n) when the length limit is a real rule of the data, such as a value defined by an external standard.
CREATE TABLE countries (
code varchar(2) NOT NULL PRIMARY KEY,
name text NOT NULL
);
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('USA', 'United States');
-- ERROR: value too long for type character varying(2)An over-long value is rejected with an error. There is one exception. An explicit cast silently truncates instead of raising an error:
SELECT 'abcdef'::varchar(3) AS truncated;This returns abc. Inserting the same value into a column does not truncate it, so the two behave differently. The standard also allows excess trailing spaces to be dropped without an error, and PostgreSQL follows that rule.
Choosing a limit
An arbitrary limit such as varchar(255) is a common habit carried over from other databases. In PostgreSQL it has no storage benefit. It only creates a rule that you may need to change later.
Changing a limit has a cost that depends on the direction:
- Increasing
n, or removing the limit, is a quick catalog change in modern PostgreSQL and does not rewrite the table. - Decreasing
nrequires PostgreSQL to scan the table to check existing values, and it takes a strong lock while it does.
If you want a length rule that is easy to change, a CHECK constraint on a text column is an alternative:
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL CHECK (char_length(sku) BETWEEN 3 AND 20)
);You can drop and replace this constraint without changing the column type. It can also express rules that varchar(n) cannot, such as a minimum length.
char(n) pads with spaces
char(n) stores exactly n characters. Shorter values are padded with trailing spaces. This surprises many people, because the padding has some odd effects.
SELECT 'ab'::char(5) AS padded,
length('ab'::char(5)) AS len,
octet_length('ab'::char(5)) AS bytes;length returns 2, because trailing spaces in a char value are treated as insignificant and ignored by length. octet_length returns 5, because the padding is physically stored.
Trailing spaces are also ignored when two char values are compared:
SELECT 'ab'::char(5) = 'ab '::char(5) AS equal_char,
'ab'::varchar(5) = 'ab '::varchar(5) AS equal_varchar;The first result is true and the second is false. In a varchar or text value, trailing spaces count.
Converting a char value to text or varchar removes the padding. This can lead to inconsistent results when you mix types in one query.
char(n) is rarely the right choice. It uses more space than varchar when values vary in length, and it is not faster. Reserve it for values that are always exactly the same length and must follow the standard's padding rules, or for compatibility with a legacy schema. Note that char with no length is the same as char(1).
Comparison across the types
The following diagram shows which choice fits which situation.
Collation and comparison
Strings are compared and sorted according to a collation, which is a set of rules for ordering characters. The collation comes from the column, the database, or an explicit COLLATE clause. The same data can sort differently under different collations.
SELECT name
FROM (VALUES ('apple'), ('Banana'), ('cherry')) AS t(name)
ORDER BY name COLLATE "C";With the "C" collation, uppercase letters sort before lowercase letters, so the result is Banana, apple, cherry. Many linguistic collations would give apple, Banana, cherry. Available collation names depend on the operating system and on how PostgreSQL was built, so check the pg_collation catalog on your server.
Comparisons with = are case-sensitive in PostgreSQL. 'Alice' = 'alice' is false. For case-insensitive matching, use lower() on both sides and index the expression:
CREATE INDEX customers_email_lower_idx ON customers (lower(email));
SELECT * FROM customers WHERE lower(email) = lower('[email protected]');Useful string functions and operators
| Function or operator | Purpose | Example result | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| `a \ | \ | b` | Concatenate | `'ab' \ | \ | 'cd'` gives `abcd` |
| `char_length(s)` | Number of characters | `char_length('héllo')` gives 5 | ||||
| `octet_length(s)` | Number of bytes | `octet_length('héllo')` gives 6 in UTF-8 | ||||
| `lower(s)`, `upper(s)` | Change case | `upper('abc')` gives `ABC` | ||||
| `trim(s)` | Remove leading and trailing spaces | `trim(' hi ')` gives `hi` | ||||
| `substring(s from 2 for 3)` | Extract part of a string | `substring('abcdef' from 2 for 3)` gives `bcd` | ||||
| `position('c' in s)` | Find a substring | `position('c' in 'abcdef')` gives 3 | ||||
| `s LIKE 'ab%'` | Pattern match | true if `s` starts with `ab` |
Concatenating with || returns NULL if either side is NULL. The concat() function treats NULL as an empty string instead:
SELECT 'a' || NULL AS with_operator,
concat('a', NULL) AS with_function;The first column is NULL and the second is a.
Common errors
- Assuming
varchar(255)is faster. It is not. Usetextunless the limit is a real rule. - Expecting truncation on insert. Inserting a value that is too long raises an error. Only an explicit cast truncates.
- Using
char(n)for short names or codes of varying length. It stores padding and compares with different rules from other string types. - Comparing
charandtextvalues and getting unexpected results. Cast both sides to the same type first. - Forgetting that
=is case-sensitive. Normalize withlower()or use an appropriate index. - Counting bytes when you mean characters. Use
char_lengthfor characters andoctet_lengthfor bytes. - Using
||with a nullable column. One NULL makes the whole result NULL.
Summary
texthas no limit and is the default choice in PostgreSQL.varchar(n)adds a length check and is the right choice when the limit is a real rule.char(n)pads with spaces and ignores trailing spaces when comparing. Avoid it in new schemas.- None of the three is faster or smaller than the others for the same data, apart from the padding in
char(n). - Comparisons are case-sensitive and depend on the collation.
Exercise
A column is declared code char(4). You insert the value 'ab'. What does octet_length(code) return in a single-byte encoding, what does length(code) return, and what does code = 'ab' return when the literal is cast to char(4)?
Show answer
octet_length(code) returns 4, because the value is stored padded with two spaces. length(code) returns 2, because trailing spaces in a char value are ignored by length. The comparison returns true, because trailing spaces are not significant when comparing char values.
Exercise
You are designing a users table. The username must be 3 to 30 characters long. Which type and constraint would you use, and why might that be better than varchar(30)?
Show answer
Use username text NOT NULL CHECK (char_length(username) BETWEEN 3 AND 30). varchar(30) can enforce only the maximum, while the CHECK constraint also enforces the minimum of 3. The constraint can also be dropped and replaced later without changing the column type.
Exercise
What does SELECT 'abcdef'::varchar(3) return, and what happens if you try to insert 'abcdef' into a varchar(3) column?
Show answer
The cast returns abc, because an explicit cast truncates silently. The insert fails with the error "value too long for type character varying(3)".