Re: Casting bytea to varchar

From: Albe Laurenz <laurenz(dot)albe(at)wien(dot)gv(dot)at>
To: "Rajagopalan, Jayashree *EXTERN*" <Jayashree(dot)Rajagopalan(at)emc(dot)com>, "pgsql-admin(at)postgresql(dot)org" <pgsql-admin(at)postgresql(dot)org>
Subject: Re: Casting bytea to varchar
Date: 2013-01-15 08:42:32
Message-ID: A737B7A37273E048B164557ADEF4A58B0579988C@ntex2010a.host.magwien.gv.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

Jayashree Rajagopalan wrote:
> I've to alter a column which is of datatype bytea to varchar(255).
>
> I used this:
> ALTER TABLE tablename ALTER COLUMN columname TYPE varchar(255);
>
> But I'm really not sure, if the value is casted properly.
> Is there a way to explicity to cast the value, while altering a columns.
>
> Example sql are welcome.

What you did is maybe not what you expect.
See the following example (9.2, encoding UTF8):

CREATE TABLE test (id integer primary key, val bytea);
INSERT INTO test VALUES (1, 'Schön'::bytea);
ALTER TABLE test ALTER COLUMN val TYPE varchar(255);
INSERT INTO test VALUES (2, 'Schön');
SELECT * FROM test;
id | val
----+----------------
1 | \x536368c3b66e
2 | Schön
(2 rows)

So the bytea column will be replaced with the string
representation of the bytea.

You cannot specify a conversion function while altering
a column's type, you'd have to use a new column like this:

ALTER TABLE test ADD COLUMN val2 varchar(255);
UPDATE test SET val2 = convert_from(val, 'UTF8'); -- because my encoding is UTF8
ALTER TABLE test DROP COLUMN val;
ALTER TABLE test RENAME COLUMN val2 TO val;

Yours,
Laurenz Albe

In response to

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message Heikki Linnakangas 2013-01-15 10:51:50 Re: Postgres WAL Recovery Fails... And Then Works...
Previous Message Albe Laurenz 2013-01-15 08:17:29 Re: Postgres WAL Recovery Fails... And Then Works...