Skip to content

Instantly share code, notes, and snippets.

@emrul
Forked from d11wtq/enum.sql
Created February 9, 2018 10:41
Show Gist options
  • Save emrul/d3cb28b6a484e6f6cd4ceba232c7187d to your computer and use it in GitHub Desktop.
Save emrul/d3cb28b6a484e6f6cd4ceba232c7187d to your computer and use it in GitHub Desktop.
Renaming an ENUM label in PostgreSQL
/*
Assuming you have an enum type like this.
You want to rename 'pending' to 'lodged'
*/
CREATE TYPE dispute_status AS ENUM('pending', 'resolved', 'open', 'cancelled');
BEGIN;
ALTER TYPE dispute_status ADD VALUE 'lodged';
UPDATE dispute SET status = 'lodged' WHERE status = 'pending';
/* if it was a default value on the column, also do this */
ALTER TABLE disputes ALTER COLUMN status SET DEFAULT 'lodged';
/* Make a new temporary type with the enum you want */
CREATE TYPE dispute_status_new AS ENUM('lodged', 'resolved', 'open', 'cancelled');
/* Migrate to the new type, specifying the cast to a string */
ALTER TABLE disputes ALTER COLUMN status SET DATA TYPE dispute_status_new USING status::text;
/* Switch the types over */
DROP TYPE dispute_status;
ALTER TYPE dispute_status_new RENAME TO dispute_status;
COMMIT;
@emrul
Copy link
Author

emrul commented Feb 9, 2018

Or

alter table disputes alter column status type dispute_status_new using
   case status 
     when 'lodged' then 'pending' 
      else status::text::dispute_status_new 
    end;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment