Postgres ENUM data type or CHECK CONSTRAINT?

前端 未结 6 1570
失恋的感觉
失恋的感觉 2021-01-29 23:24

I have been migrating a MySQL db to Pg (9.1), and have been emulating MySQL ENUM data types by creating a new data type in Pg, and then using that as the column definition. My q

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 23:52

    I'm hoping somebody will chime in with a good answer from the PostgreSQL database side as to why one might be preferable to the other.

    From a software developer point of view, I have a slight preference for using check constraints, since PostgreSQL enum's require a cast in your SQL to do an update/insert, such as:

    INSERT INTO table1 (colA, colB) VALUES('foo', 'bar'::myenum)
    

    where "myenum" is the enum type you specified in PostgreSQL.

    This certainly makes the SQL non-portable (which may not be a big deal for most people), but also is just yet another thing you have to deal with while developing applications, so I prefer having VARCHARs (or other typical primitives) with check constraints.

    As a side note, I've noticed that MySQL enums do not require this type of cast, so this is something particular to PostgreSQL in my experience.

提交回复
热议问题