I have one MySQL table, users
, with the following columns:
To manage a roles system, would there be a downside to either of the following options?
Option 1:
Create a second table called roles
with three columns: role_id
(Primary key), name
, and description
, then associate users.user_id
with roles.role_id
as foreign keys in a third table called users_roles
?
Or...
Option 2:
Create a second table called roles
with two columns: user_id
(Foreign key from users.user_id
) and role
(ENUM)? The ENUM datatype column would allow for a short list of allowable roles to be inserted as values.
I've never used the ENUM datatype in MySQL before, so I'm just curious, as option 2 would mean one less table. I hope that makes sense, this is the first time I've attempted to describe MySQL tables in a forum.
An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time. See Section 11.3. 1, “String Data Type Syntax” for ENUM type syntax and length limits.
For ENUM , the value is inserted as the error member ( 0 ). For SET , the value is inserted as given except that any invalid substrings are deleted. For example, 'a,x,b,y' results in a value of 'a,b' .
Benefits of Enum data type – It also provides readable queries and output easily because the numbers can be translated back to the result of the corresponding string.
The ENUM data type, different from standard data types, is an enumerated list of 1 to 65,535 strings indicating the allowed values for the field. When defining an ENUM, you are creating a list of items from which the value must be selected (or it can be NULL).
In general, ENUM
types are not meant to be used in these situations. This is especially the case if you intend to cater for the flexibility of adding or removing roles in the future. The only way to change the values of an ENUM
is with an ALTER TABLE
, while defining the roles in their own table will simply require a new row in the roles
table.
In addition, using the roles
table allows you to add additional columns to better define the role, like the description
field you suggested in Option 1. This is not possible if you were to use an ENUM
type as in Option 2.
Personally I would not opt for an ENUM
in these scenarios. Maybe I can see them being used for columns with an absolutely finite set of values, such as {Spades, Hearts, Diamonds, Clubs}
to define the suit of a card, but not in cases such as the one in question, for the disadvantages mentioned earlier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With