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)?
-
3Why don't you use PG's enum type? Why do you think you need to "emulate" one? – Jun 08 '12 at 07:31
6 Answers
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
CREATE TYPE valid_colors AS ENUM ('red', 'green', 'blue'); CREATE TABLE t ( color VALID_COLORS );
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.
SELECT n.nspname AS enum_schema, t.typname AS enum_name, e.enumlabel AS enum_value FROM pg_type t JOIN pg_enum e ON t.oid = e.enumtypid JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE t.typname = 'valid_colors' enum_schema | enum_name | enum_value -------------+---------------+------------ public | valid_colors | red public | valid_colors | green public | valid_colors | blue
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
SELECT FROM t WHERE color LIKE 'bl%';
Check constraints
CREATE TABLE t ( colors TEXT CHECK (colors IN ('red', 'green', 'blue')) );
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
CREATE TABLE valid_colors ( id SERIAL PRIMARY KEY NOT NULL, color TEXT ); INSERT INTO valid_colors (color) VALUES ('red'), ('green'), ('blue'); CREATE TABLE t ( color_id INTEGER REFERENCES valid_colors (id) );
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_id
to the desired text value.

- 965
- 11
- 15

- 13,598
- 26
- 66
- 101
-
-
12Also, with another table and a foreign key, you can delegate the management of colors to an ordinary user without letting them alter tables. – Mike Sherrill 'Cat Recall' Jun 11 '12 at 22:37
-
2From an *abstract perspective* I see no diff in 1) and 3) .. The idea is the same, diff being that PG created the REF table. Either way I can easily select/view/alter the valid options from that REF table. Don't forget that it would be slick to dynamically create a list of valid options in the UI based on the optional values in the DB. Not so simple with 2). Very simple with 1).. or 3) using something like: CREATE VIEW vw_enums AS SELECT t.typname, e.enumlabel, e.enumsortorder FROM pg_enum e JOIN pg_type t ON e.enumtypid = t.oid; For portability this view easily dumps for use as a REF table. – Michael M Apr 07 '13 at 03:31
-
5try: SELECT FROM lower( t::text ) WHERE color LIKE 'bl%'; this will convert the column values to text for searching. – Tim Child Oct 02 '16 at 19:55
-
1I think that option (2) has the disadvantage of requiring a table lock when updating the valid enum values (e.g., adding a valid value). – Bill Jul 23 '17 at 22:01
-
@S-Man Why is inserting hard? PostgreSQL has `BEFORE` and `AFTER` for inserting new values into an enum at arbitrary positions. – Eugene Pakhomov Jul 24 '19 at 10:09
-
1@EugenePakhomov Yes, you are right. Changing values of enums is quite hard, especially renaming and deleting values. Only operation which works well is appending. Foreign keys do not have such problems... – S-Man Jul 24 '19 at 10:20
-
1IMHO, CHECKs implement business logic, ENUMs are labeled scalar values, and FKs describe entities that you work with. When in doubt, always choose FKs, because they allow delegation and fine grained authorization, for example in conjunction with row level security. – Code4R7 Aug 08 '21 at 07:17
As other answers point out, check constraints have flexibility issues, but setting a foreign key on an integer id requires joining during lookups. Why not just use the allowed values as natural keys in the reference table?
To adapt the schema from punkish's answer:
CREATE TABLE valid_colors (
color TEXT PRIMARY KEY
);
INSERT INTO valid_colors (color) VALUES
('red'),
('green'),
('blue');
CREATE TABLE t (
color TEXT REFERENCES valid_colors (color) ON UPDATE CASCADE
);
Values are stored inline as in the check constraint case, so there are no joins, but new valid value options can be easily added and existing values instances can be updated via ON UPDATE CASCADE
(e.g. if it's decided "red" should actually be "Red", update valid_colors
accordingly and the change propagates automatically).

- 1
- 1

- 965
- 11
- 15
-
1This seems like a very interesting approach indeed. Does anybody know if there are any known downsides specific to this? – Natan Streppel Dec 23 '20 at 13:52
-
3Yes, it takes space to store all of those values, which potentially can cause performance problems. However, it is still a great option due to its simplicity. Basically, it's option 3 "Foreign Key" but without using the id for referencing. Brilliant! – IvanD Mar 06 '21 at 19:29
-
let me know if I got this right, it stores 'value' in table t so there is no need to do join during lookups but it also connects to valid_colors and if color updates, spelling changes, it'd also update all rows in table t with new spelling? – Muhammad Umer Apr 05 '21 at 00:40
-
That's right - not ideal if the color names are constantly changing (as the rows in t will be constantly updating as well), but if you're dealing with a small, static set of values, that shouldn't be an issue. – Gord Stephen May 06 '21 at 21:37
One of the big disadvantages of Foreign keys vs Check constraints is that any reporting or UI displays will have to perform a join to resolve the id to the text.
In a small system this is not a big deal but if you are working on a HR or similar system with very many small lookup tables then this can be a very big deal with lots of joins taking place just to get the text.
My recommendation would be that if the values are few and rarely changing, then use a constraint on a text field otherwise use a lookup table against an integer id field.

- 451
- 7
- 6
-
Using the "color" name as ID might solve this https://stackoverflow.com/a/41655273/3484824 though surely can have its own concerns as stated in the comments on that answer – Can Rau Sep 26 '22 at 23:59
PostgreSQL has enum types, works as it should. I don't know if an enum is "better" than a constraint, they just both work.

- 117,544
- 24
- 142
- 135
-
9Personally I prefer using a check constraint (or even a lookup table with a FK constraint) for these kind of things. It makes changing them later easier. – Jun 08 '12 at 07:31
From my point of view, given a same set of values
- Enum is a better solution if you will use it on multiple column
- If you want to limit the values of only one column in your application, a check constraint is a better solution.
Of course, there is a whole lot of other parameters which could creep in your decision process (typically, the fact that builtin operators are not available), but I think these two are the most prevalent ones.

- 2,725
- 2
- 23
- 39
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.

- 13,679
- 10
- 57
- 69
-
2an additional issue with ENUM types is that string operators don't work. For example, if I have an ENUM field with text options, I can't use LIKE on it. On the other hand, with CHECK CONSTRAINTS text would still be treated as text. – punkish Jun 10 '12 at 18:40
-
1For PostgreSQL again - agreed. I've seen this as well and should have thought of it for my answer. I did just go and test it in MySQL as well and there again MySQL doesn't impose that restriction - you can use LIKE with an enum. So my vote with PostgreSQL is to avoid enums unless there is some other good reason to use them that I'm not aware of. – quux00 Jun 11 '12 at 01:55
-
2The original claim seems to be no longer valid: The `::myenum` suffix is not mentioned in the current postgres documentation: http://www.postgresql.org/docs/current/static/datatype-enum.html – rluba Mar 08 '16 at 19:44