Skip to content

PostgreSQL varchar Limits: Characters, Bytes and Spaces

PostgreSQL varchar(n) limits the number of characters in a value. Use char_length(value) to inspect that count and octet_length(value) for its encoded bytes. Check the original input before an explicit cast can shorten it.

The PostgreSQL 18 character-type reference defines the limit. A two-character column can hold one 😀 in a UTF8 database even though that emoji occupies four bytes.

Check encoding before comparing counts

Read SHOW server_encoding;, SHOW client_encoding; and SHOW standard_conforming_strings; on your connection. The examples below require UTF8 and standard-conforming strings set to on. PostgreSQL’s encoding documentation explains why client and server settings can differ; a byte count needs that context.

These exact strings were checked in an isolated UTF8 PostgreSQL runtime. The combining-accent row contains U+0065 followed by U+0301. Its count differs from precomposed U+00E9, despite their similar appearance.

Text valueCharactersUTF8 bytes
A11
é (U+00E9)12
e + U+030123
😀 (U+1F600)14

The string-function reference defines both measurements. Neither promises a user-perceived character count. For that distinction, see the String Length guide.

Run a diagnostic without writing rows

This query measures only its literal sample values. The Unicode string syntax makes the accent and emoji sequences explicit. Results appear in the table’s order.

WITH sample(ord, label, value) AS (
  VALUES (1, 'A', 'A'::text),
         (2, 'precomposed', U&'\00E9'),
         (3, 'combining', U&'e\0301'),
         (4, 'emoji', U&'\+01F600')
)
SELECT label, char_length(value) AS characters,
       octet_length(value) AS bytes
FROM sample ORDER BY ord;

Separate a cast from a length check

Assigning an overlong value to a constrained column normally raises an error. An explicit cast can instead truncate it. This read-only example returns ab:

SELECT 'abc'::varchar(2) AS shortened; -- ab

A count taken after that cast cannot reveal the original third character. Measure the uncast input when deciding whether it exceeds your field rule. There is also an assignment exception: excess characters consisting entirely of spaces are discarded to fit. For varchar(2), 'a ' becomes 'a '; the retained space still counts.

Account for fixed-width char padding

char(3) pads a one-letter value with spaces. The character count strips trailing spaces through conversion to text, while the direct octet_length(character) overload retains them:

SELECT char_length('a'::char(3)) AS characters,
       octet_length('a'::char(3)) AS bytes;
-- characters = 1, bytes = 3

Here the byte result includes two padding spaces. It measures the encoded value rather than the database file or storage overhead. Keep the original value, data type, encoding and conversion step beside each measurement. If the data is in SQLite, use its separate SQLite length guide; its value and NUL rules differ.