Video in progress

How do you store enum-like values such as a status in the database: the PostgreSQL `ENUM` type, `text` + `CHECK`, or a separate lookup table?

In most cases I choose text + CHECK: it's easy to read, and adding a new value is a simple migration. PostgreSQL ENUM is compact, but removing or renaming a value is awkward. A lookup table is good when a value needs extra data (a name, an order).

📖 Answer

How the three options differ in practice:

ENUM type text + CHECK lookup table + FK
Size 4 bytes string length size of the id
New value ALTER TYPE ... ADD VALUE recreate the CHECK INSERT
Removing a value hard easy easy
Extra attributes no no yes
ALTER TABLE orders
  ADD CONSTRAINT orders_status_chk
  CHECK (status IN ('NEW', 'PAID', 'SHIPPED', 'CANCELLED'));

On the Java side I use @Enumerated(EnumType.STRING). ORDINAL is dangerous: if a new value is added in the middle of the enum, all the numbers in the database take on a different meaning.

To work with a PostgreSQL ENUM in Hibernate 6 you need @JdbcTypeCode(SqlTypes.NAMED_ENUM), otherwise the driver raises an error when writing a varchar into an enum column.

One thing: changing a CHECK on a big table validates the whole table. If you add it with NOT VALID and then run VALIDATE CONSTRAINT separately, the lock is short.