How would I implement a enumeration field in a database that doesn’t support enumerations? (i.e. SQLite)
The fields need to be easily searchable with ‘field = ?’ so using any type of data serialization is a bad idea.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using a foreign key to a lookup table is the approach I use. In fact, I use this even when I do use a database that supports ENUM (e.g. MySQL).
For simplicity, I may skip the ever-present ‘
id‘ for the lookup table, and just use the actual value I need in my main table as the primary key of the lookup table. That way you don’t need to do a join to get the value.Admittedly, storing strings takes more space than MySQL’s implementation of
ENUM, but unless the table in question has millions of rows, it hardly matters.Other advantages of the lookup table are that you can add or remove a value from the list with a simple
INSERTorDELETE, whereas withENUMyou have to useALTER TABLEto redefine the list.Also try querying the current list of permitted values in an
ENUM, for instance to populate a pick-list in your user interface. It’s a major annoyance! With a lookup table, it’s easy:SELECT status from BugStatus.Also you can add other attribute columns to the lookup table if you need to (e.g. to mark choices available only to administrators). In an
ENUM, you can’t annotate the entries; they’re just simple values.Another option besides a lookup table would be to use
CHECKconstraints (provided the database supports them — MySQL doesn’t support CHECK until version 8.0.16):But this use of a
CHECKconstraint suffers from the same disadvantages as theENUM: hard to change the list of values withoutALTER TABLE, hard to query the list of permitted values, hard to annotate values.PS: the equality comparison operator in SQL is a single
=. The double==has no meaning in SQL.