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 question -- could I, and would it be better to, use a CHECK CONSTRAINT instead? The MySQL ENUM types are implemented to enforce specific values entries in the rows. Could that be done with a CHECK CONSTRAINT? and, if yes, would it be better (or worse)?
|
Based on the comments and answers here, and some rudimentary research, I have the following summary to offer for comments from the Postgres-erati. Will really appreciate your input. There are three ways to restrict entries in a Postgres database table column. Consider a table to store "colors" where you want only 'red', 'green', or 'blue' to be valid entries.
|
|||||||||
|
PostgreSQL has enum types, works as it should. I don't know if an enum is "better" than a constraint, they just both work. |
|||||
|
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:
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. |
|||||||
|