Re: How to modify ENUM datatypes?

From: Craig Ringer <craig(at)postnewspapers(dot)com(dot)au>
To: "D(dot) Dante Lorenso" <dante(at)lorenso(dot)com>
Cc: Postgres-General <pgsql-general(at)postgresql(dot)org>
Subject: Re: How to modify ENUM datatypes?
Date: 2008-04-22 12:58:30
Message-ID: 480DE0F6.50706@postnewspapers.com.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

D. Dante Lorenso wrote:
>
> The problem is that once I create a column in my account table that
> uses this 'account_type' datatype, I can't seem to change or add to it
> any more. I want to add a new value or edit/delete an existing one.
>
> How do you make changes to an ENUM datatype that is already in use?
>
As far as I know ENUM is not well suited to uses where new enumeration
members may be added later. A lookup table and a foreign key is probably
better for this sort of use.

You *can* add elements to an enum type - sort of - by creating a new
type and converting columns. It's ugly, though, and will be hard to get
right when the column of interest is referenced by foreign keys and such.

One way to do it if you really must:

-- Starting state

CREATE TYPE et1 AS ENUM('yes','no');
CREATE TABLE testtab (
a et
);
INSERT INTO testtab (a) values ('yes');

-- Change
CREATE TYPE et2 AS ENUM('yes','no','filenotfound');
ALTER TABLE testtab ALTER COLUMN a TYPE et2 USING (
CASE a WHEN 'yes' THEN 'yes'::et2 WHEN 'no' THEN 'no'::et2 END
);

-- Alternative ALTER that's suitable if you're not removing anything
from the enum
ALTER TABLE testtab ALTER COLUMN a TYPE et2 USING ( a::text::et2 );

Personally, though, I'd stick to the good 'ol lookup table and foreign key.

--
Craig Ringer

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Thomas Kellerer 2008-04-22 13:06:54 Re: How is statement level read consistency implemented?
Previous Message Roberts, Jon 2008-04-22 12:56:34 Re: How is statement level read consistency implemented?