Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Change Enum Values

In my table named "stocktakings", there is a column from type ENUM called "status". "status" has the following fields:

  • 'Pending'
  • 'Processing'
  • 'Failed'
  • 'Succeeded'

I want to change the values to:

  • 'ready for relocation'
  • 'search shelf location'
  • 'stock update succeeded'
  • 'stock update failed'
  • 'updating stock'

I tried the following command:

ALTER TABLE `stocktakings` MODIFY `stocktakings.status` 
    `stocktakings.status` ENUM(
        `ready_for_relocation`,
        `search_shelf_location`,
        `stock_update_succeeded`,
        `stock_update_failed`,
        `updating_stock`
);

Didn't work. Any ideas?

like image 634
David Lambauer Avatar asked Oct 31 '18 07:10

David Lambauer


1 Answers

You cannot just remove the Old Enum values from the Column definition. Otherwise, there will be an irreparable Data loss (all fields may turn to blank). It will be a multi-step process:

Add new Enum Values to Existing Column definition. Also, Enum values are surrounded by single quotes (not backticks)

ALTER TABLE `stocktakings` MODIFY `stocktakings`.`status` ENUM(
        'Pending', 
        'Processing', 
        'Failed', 
        'Succeeded', 
        'ready_for_relocation',
        'search_shelf_location',
        'stock_update_succeeded',
        'stock_update_failed',
        'updating_stock'
);

Now, run an Update query to Update all the enum values correspondingly:

UPDATE `stocktakings` 
SET status = CASE status 
               WHEN 'Pending' THEN 'ready_for_relocation'
               WHEN 'Processing' THEN 'search_shelf_location'
               WHEN 'Failed' THEN 'stock_update_failed'
               WHEN 'Succeeded' THEN 'stock_update_succeeded'
             END 

Now, Alter Table and remove the Old enum values.

ALTER TABLE `stocktakings` MODIFY `stocktakings`.`status` ENUM(
            'ready_for_relocation',
            'search_shelf_location',
            'stock_update_succeeded',
            'stock_update_failed',
            'updating_stock'
    );
like image 164
Madhur Bhaiya Avatar answered Sep 23 '22 04:09

Madhur Bhaiya