Upgrading a varchar column to enum type in postgresql

前端 未结 3 1614
别跟我提以往
别跟我提以往 2020-12-09 09:15

We have a varchar column in a table, that we need to upgrade to enum type.

All the values in the varchar column are valid values in the enumeration. There is no null

相关标签:
3条回答
  • 2020-12-09 09:52

    You need to define a cast to be used because there is no default cast available.

    If all values in the varcharColumn comply with the enum definition, the following should work:

    alter table foo 
      ALTER COLUMN varcharColumn TYPE enum_type using varcharColumn::enum_type;
    

    I personally don't like enums because they are quite unflexible. I prefer a check constraint on a varchar column if I want to restrict the values in a column. Or - if the list of values changes often and is going to grow - a good old "lookup table" with a foreign key constraint.

    0 讨论(0)
  • 2020-12-09 09:55

    you as well might consider domain type if you dont need the enum ordering property and are offput by missing delete enum value.
    Domain types are user-denfiend types + constraints, which makes x out of a selection possible via CHECK & co and as such not so 'unwieldy like enums.

    Typical enum is eg log levels, while domain eg email text input validation with the field being present in many tables.

    0 讨论(0)
  • 2020-12-09 10:04

    Got it.

    ALTER TABLE tableName
       ALTER COLUMN varcharColumn TYPE enum_type
        USING varcharColumn::enum_type
    

    will update it successfully.

    0 讨论(0)
提交回复
热议问题