Select truncated string from Postgres

Some Guy picture Some Guy · Oct 8, 2015 · Viewed 10k times · Source

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?

Answer

Erwin Brandstetter picture Erwin Brandstetter · Oct 8, 2015

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), where n is a positive integer. Both of these types can store strings up to n 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)

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 to n characters without raising an error. (This too is required by the SQL standard.)