MySQL Change a column ENUM value

MysqlEnums

Mysql Problem Overview


I have a MySQL table "content" which has a column page_type of type ENUM. The ENUM values are NEWS & PRESS_RELEASE. I need to replace NEWS with FEATURED_COVERAGE:

ALTER TABLE `content` CHANGE `pagetype` `pagetype` ENUM('FEATURED_COVERAGE','PRESS_RELEASE') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

But now the records in the table, which earlier had page_type NEWS are now empty, and there is no way that I can identify which records are NEWS, so that I can rename those to FEATURED_COVERAGE.

How to resolve such issues?

Mysql Solutions


Solution 1 - Mysql

If I understand your question, you want to rename the existing enum value NEWS to FEATURED_COVERAGE. If so, you need to follow below steps,

  1. Alter the table and add the new enum value to the column, so that you will have 3 enums

    ALTER TABLE `content` CHANGE `pagetype` `pagetype`
    ENUM('FEATURED_COVERAGE','PRESS_RELEASE', 'NEWS') CHARACTER SET utf8
    COLLATE utf8_general_ci NOT NULL;
    
  2. Set the old enum value to new value for all records.

    UPDATE `content` set `pagetype` = 'FEATURED_COVERAGE' where
    `pagetype` = 'NEWS';
    
  3. Alter the table and drop the old enum value.

    ALTER TABLE `content` CHANGE `pagetype` `pagetype`
    ENUM('FEATURED_COVERAGE','PRESS_RELEASE') CHARACTER SET utf8 COLLATE
    utf8_general_ci NOT NULL;
    

Solution 2 - Mysql

MySQL's enum always has a hidden option which is 0 as integer and '' as string. When you try to assign an invalid value it uses the hidden one.

Assuming all your empty values were 'NEWS' before the update you can change them with

UPDATE content SET pagetype = 'FEATURED_COVERAGE' WHERE pagetype = 0

Solution 3 - Mysql

I think default might have helped.

ALTER TABLE `content`
CHANGE `pagetype` `pagetype` ENUM('FEATURED_COVERAGE','PRESS_RELEASE') 
   CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULt 'FEATURED_COVERAGE';

Now you have to blindly to an update

And never use an enum column if your value set is changing.

Solution 4 - Mysql

Since you have changed only one enum it will not be difficult for you

Try using this

UPDATE content SET pagetype = 'FEATURED_COVERAGE' WHERE pagetype = 0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSangram AnandView Question on Stackoverflow
Solution 1 - MysqlAbimaran KugathasanView Answer on Stackoverflow
Solution 2 - MysqlVatevView Answer on Stackoverflow
Solution 3 - Mysqlgeorgecj11View Answer on Stackoverflow
Solution 4 - MysqlalwaysLearnView Answer on Stackoverflow