← Back to PostgreSQL, page 1

postgresql-0001 · Easy fresher

How do text, varchar(n) and char(n) behave in PostgreSQL, and which should a new column use?

text and varchar without a length are the same storage type with no limit. varchar(n) rejects longer values with an error, and char(n) pads values with spaces to n characters, which causes surprising comparisons. Most columns should be text, with a CHECK constraint if a length rule is a business rule.

Full answer

Setup for the example:

sql
CREATE TABLE codes (
  t  text,
  v  varchar(5),
  c  char(5)
);
INSERT INTO codes VALUES ('ab', 'ab', 'ab');
sql
SELECT length(t) AS t_len, length(v) AS v_len, octet_length(c) AS c_bytes, c = 'ab' AS c_equal, '[' || c || ']' AS c_concat FROM codes;

Output:

text
 t_len | v_len | c_bytes | c_equal | c_concat
-------+-------+---------+---------+----------
 2     | 2     | 5       | t       | [ab]
(1 row)
sql
INSERT INTO codes (v) VALUES ('toolong');

PostgreSQL returns:

text
ERROR:  value too long for type character varying(5)

The char(5) value is stored padded to five bytes, yet compares equal to 'ab' and loses its padding when concatenated, because trailing spaces are treated as insignificant for char. Inserting seven characters into varchar(5) fails with an error naming the type. There is no performance advantage to varchar(n) or char(n) in PostgreSQL; changing a length limit later needs an ALTER, while a CHECK (length(col) <= n) is easier to change and can carry a clear name.

sql
CREATE TABLE codes (
  t  text,
  v  varchar(5),
  c  char(5)
);
INSERT INTO codes VALUES ('ab', 'ab', 'ab');

SELECT length(t) AS t_len, length(v) AS v_len, octet_length(c) AS c_bytes, c = 'ab' AS c_equal, '[' || c || ']' AS c_concat FROM codes;

INSERT INTO codes (v) VALUES ('toolong');

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • text and varchar have the same storage
  • varchar(n) errors on longer values
  • char(n) pads with spaces
  • No speed benefit to length limits
  • Use CHECK constraints for business length rules

Common mistakes

  • Using char(n) for variable-length codes
  • Picking varchar(255) by habit

Follow-ups

  • How would you enforce a maximum length that may change?
  • How does citext differ from text?

Tips

  • Recommend text plus CHECK