4

I have a column called "abc_integer" which holds value of a foriegn key of a table which is only 2 values (1, 2). So I want to drop this column and add a new column "abc_enum" Note : I am trying this in Postgres 9.3 version

CREATE TYPE abc_enum_type ENUM AS ('hi', 'hello');
ALTER TABLE abc ADD COLUMN abc_enum abc_enum_type ;
UPDATE abc SET abc_enum = CASE 
           WHEN abc_integer == 1 THEN 'hi'::abc_enum_type
           ELSE 'hello'::abc_enum_type END ;
ALTER TABLE abc DROP COLUMN abc_intger;

Is there a better way doing this ? Like accommodating all of these in a single statement Alter type and rename with USING clause ?

Thanks in Advance!

1 Answer 1

8

You can "compress" it by one step with USING, like:

alter table abc alter COLUMN abc_integer set data type abc_enum_type using case when abc_integer == 1 THEN 'hi'::abc_enum_type ELSE 'hello'::abc_enum_type END;

and then renaming the column abc_integer to abc_enum.

If that what you want it works on 9.3

Btw! Mind default values.

Edit The way you do it does not lock the table. While altering column type will!

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks !! I don't have any default values .
Is both the above mentioned same ? Both will take same time to execute? Because for one we are changing type , on other hand we are updating for new column .
yeah. forgot to mention :)
Is there a way to accommodate the default value too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.