I have some large varchar
values in Postgres that I want to SELECT and move somewhere else. The place they are going to uses VARCHAR(4095)
so I only need at most 4095 bytes (I think that's bytes) and some of these varchars are quite big, so a performance optimization would be to SELECT a truncated version of them.
How can I do that?
Something like:
SELECT TRUNCATED(my_val, 4095) ...
I don't think it's a character length though, it needs to be a byte length?
The n
in varchar(n)
is the number of characters, not bytes. The manual:
SQL defines two primary character types:
character varying(n)
andcharacter(n)
, wheren
is a positive integer. Both of these types can store strings up ton
characters (not bytes) in length.
Bold emphasis mine.
The simplest way to "truncate" a string would be with left()
:
SELECT left(my_val, 4095)
Or just cast:
SELECT my_val::varchar(4095)
If one explicitly casts a value to
character varying(n)
orcharacter(n)
, then an over-length value will be truncated ton
characters without raising an error. (This too is required by the SQL standard.)