SQL: Advantages of an ENUM vs. a one-to-many relationship?

后端 未结 7 2075
独厮守ぢ
独厮守ぢ 2021-02-07 04:14

I very rarely see ENUM datatypes used in the wild; a developer almost always just uses a secondary table that looks like this:

CREATE TABLE officer_ranks (
id in         


        
7条回答
  •  清歌不尽
    2021-02-07 05:10

    A small advantage may lie in the fact, that you have a sort of UDT when creating an ENUM. A user defined type can be reused formally in many other database objects, e.g. in views, other tables, other types, stored procedures (in other RDBMS), etc.

    Another advantage is for documentation of the allowed values of a field. Examples:

    • A yes/no field
    • A male/female field
    • A mr/mrs/ms/dr field

    Probably a matter of taste. I prefer ENUMs for these kinds of fields, rather than foreign keys to lookup tables for such simple concepts.

    Yet another advantage may be that when you use code generation or ORMs like jOOQ in Java, you can use that ENUM to generate a Java enum class from it, instead of joining the lookup table, or working with the ENUM literal's ID

    It's a fact, though, that only few RDBMS support a formal ENUM type. I only know of Postgres and MySQL. Oracle or DB2 don't have it.

提交回复
热议问题