9

I currently have a Postgres 8.4 database that contains a varchar(10000) column. I'd like to change this into a varchar(255) and truncate any data that happens to be too long. How can I do this?

William Jones
  • 18,089
  • 17
  • 63
  • 98

3 Answers3

18

Something like ALTER TABLE t ALTER COLUMN c TYPE VARCHAR(255) USING SUBSTR(c, 1, 255)

mkj
  • 2,761
  • 5
  • 24
  • 28
5

1) Update the column data using a substring method to truncate it

update t set col = substring(col from 1 for 255)

2) Then alter the table column

alter table t alter column col type varchar(255)

Docs here http://www.postgresql.org/docs/8.4/static/sql-altertable.html

Ryan McGeary
  • 235,892
  • 13
  • 95
  • 104
codenheim
  • 20,467
  • 1
  • 59
  • 80
  • 2
    it seems with more recent pgsql it would be: update t set col = substring(col from 1 for 255) ("for" replaces "to") – user1051849 Oct 09 '15 at 09:27
1
BEGIN;
UPDATE table SET column = CAST(column as varchar(255));
ALTER TABLE table ALTER COLUMN column TYPE varchar(255); --not sure on this line. my memory is a bit sketchy
COMMIT;
Earlz
  • 62,085
  • 98
  • 303
  • 499