The n in varchar(n) is the number of characters, not bytes. The manual:
SQL defines two primary character types:
character varying(n)and
character(n), wherenis a positive integer. Both of these types can
store strings up toncharacters (not bytes) in length.
Bold emphasis mine.
Use left() to “truncate” a string to a given number of characters:
SELECT left(my_val, 4095);
Or cast:
SELECT my_val::varchar(4095);
The manual once more:
If one explicitly casts a value to
character varying(n)or
character(n), then an over-length value will be truncated ton
characters without raising an error. (This too is required by the SQL standard.)
The former returns text and is typically preferable – unless you expressly need the type varchar(4095). The result will be coerced to text in most contexts anyway.