views:

777

answers:

3

For example, I have a "users" table which has an enum column "type" with two possible values: "individual" and "organization." They are mutually exclusive and mandatory (each row must have exactly one value from the possible two. Would this be a good case to use enums? Why so/not?

What are some pros and cons on using ENUM (set) types for database fields?

+6  A: 

Yes, this seems like a good candidate for an enum.

Pros:

  • Small (disk space)
  • Fast (integer comparison)
  • Easy to understand (mostly)

Cons:

  • Can't add a value without changing the table structure
  • Have to be careful with case sensitivity in places
  • Can be very confusing if used badly... don't use active = enum('1', '0') as I have to put up with!
  • Not supported by all databases
Greg
+1 (I'd would add the "locking-in" to a certain DB server product to the Cons)
Tomalak
What is wrong with active=enum(1,0) ?
Tom
active = 0 is not the same as active = '0' !
Greg
Added, thanks Tomalak
Greg
+3  A: 

Personally I've always preferred to have standard int columns for this, with a foreign key linking to a description table. This enables you to limit the values for the type id column.

Of course this can lead to table bloat, but it does allow you to have a "localised" table to go with the description table, so that your applications can display localised content in dropdowns/reports etc where necessary.

User.UserTypeID -> UserType.UserTypeID -> UserTypeLocalised.UserTypeID where locality = ??

This is also more database-agnostic and therefore more easily ported to different platforms.

Additionally, it doesn't sound right for a user to be either an individual or an organisation. I would expect a user to be part of an organisation, which would require an Organisation table and the user to have an OrganisationID column, instead. User type would typically be more likely a "Human/system" differentiation (assuming your systems use ambient logons to perform operations and you want to have auditing).

Neil Barnwell
+2  A: 

Putting the reference data into a table with a foreign key means that the database can enforce a data integrity rule. You can also add a different type (e.g. 'Internal' or 'Non-Profit') without having to extend the database schema. Finally, you can annotate the reference table with flags or other coding to allow you to implement data driven business logic if desired.

ConcernedOfTunbridgeWells