Last active
November 1, 2018 10:19
-
-
Save ludwinas/f2a5509b8f073965d73bdbfab0df07b8 to your computer and use it in GitHub Desktop.
Renaming an ENUM value in Postgres 9.5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- assuming your existing type is as follows | |
CREATE TYPE user_types AS ENUM | |
( 'user', | |
'admin', | |
'foo' | |
); | |
-- here's how you rename the 'foo' value to 'bar' | |
BEGIN; | |
ALTER TABLE users ALTER COLUMN user_type SET DATA TYPE TEXT; | |
-- if the column has a default value | |
ALTER TABLE users ALTER COLUMN user_type SET DEFAULT 'user'; | |
DROP TYPE user_types; | |
UPDATE users SET user_type = 'bar' WHERE user_type = 'foo'; | |
CREATE TYPE user_types AS ENUM | |
( 'user', | |
'admin', | |
'bar' | |
); | |
-- once more, if the column has a default value change the default before changing the column | |
-- type, else Postgres won't know how to convert the existing default value to the new type | |
ALTER TABLE users ALTER COLUMN user_type SET DEFAULT 'user'::user_types; | |
ALTER TABLE users ALTER COLUMN user_type SET DATA TYPE user_types USING user_type::user_types; | |
COMMIT; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment