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)?
Share
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.
Enumerated data type
Advantages are that the type can be defined once and then reused in as many tables as needed. A standard query can list all the values for an ENUM type, and can be used to make application form widgets.
Disadvantages are, the ENUM type is stored in system catalogs, so a query as above is required to view its definition. These values are not apparent when viewing the table definition. And, since an ENUM type is actually a data type separate from the built in NUMERIC and TEXT data types, the regular numeric and string operators and functions don’t work on it. So, one can’t do a query like
Check constraints
Two advantage are that, one, “what you see is what you get,” that is, the valid values for the column are recorded right in the table definition, and two, all native string or numeric operators work.
Foreign keys
Essentially the same as creating an ENUM type, except, the native numeric or string operators work, and one doesn’t have to query system catalogs to discover the valid values. A join is required to link the
color_idto the desired text value.