Question

I am working on limiting input in certain fields in my Postgres database, and I have a working solution using ENUM like so:

CREATE TYPE label AS ENUM ('foo','bar');

However, I was browsing around and looking at alternative ways of doing this using:

  • constraints (eg. CHECK (type IN ('foo','bar')) )
  • triggers (slow, from what I've read)
  • foreign keys

What are the advantages/disadvantages of using either of these methods, would any of these be more advisable? I am not necessarily asking which one is the 'best' method, only what kind of issues may arise from using these, ie. I know that using triggers might be quite slow compared to the other methods, but perhaps could deal with some more complex input conditions.

Était-ce utile?

La solution

Maybe not all the differences, but most important in my opinion :

  1. enum vs text/varchar + check constraint.

    • enum values are internally stored as integer numbers, so different storage requirements
    • ordering : order of enum values corresponds order in which values were entering during creation type, so for enum ('small', 'big') small < big; for text column 'big'<'small'
  2. enum vs foreign key

    • performance-wise they should behave very similar, but you can bypass foreign key constraint by, for instance, disabling all triggers or changing session replication role
    • there is a bigger difference from data model perspective. If something has attributes, needs to be tracked, likely to be modified in either way, it should be stored as a separate entity in its own table. If it's just an attribute , e.g. color in many cases, then it's fine to store it as a enumerated type.

Triggers are just not the right tool to implement check constraints. They add complexity, hide logic, add maintenance overhead. In some cases they are "necessary evil" , but they definitely shouldn't be used just to do what check constraint can do.

Licencié sous: CC-BY-SA avec attribution
Non affilié à dba.stackexchange
scroll top