
MySQL ENUM
The MySQL ENUM
data type is used to store a list of predefined values within a column. An ENUM
column can store one of the enumerated values, which are defined during the table creation. This is useful when you have a specific set of values that a column can take, and you want to enforce data integrity by allowing only those values.
The basic syntax for creating an ENUM
column in a MySQL table is as follows:
column_name ENUM('value1', 'value2', ..., 'valueN')
column_name
: The name of the column.'value1', 'value2', ..., 'valueN'
: The list of allowed values for the column.
Here’s an example of how to create a table with an ENUM
column:
CREATE TABLE colors (
color_id INT,
color_name ENUM('Red', 'Green', 'Blue', 'Yellow')
);
In this example, the color_name
column is defined as an ENUM
that can only store one of the four specified values: ‘Red’, ‘Green’, ‘Blue’, or ‘Yellow’.
To insert data into an ENUM
column, you need to use one of the predefined values:
INSERT INTO colors (color_id, color_name) VALUES (1, 'Red');
You can also query data using the ENUM
values:
SELECT * FROM colors WHERE color_name = 'Green';
Keep in mind the following when working with ENUM
:
- The values stored in an
ENUM
column are case-insensitive. ‘Red’ and ‘red’ are treated as the same value. - You cannot add new values to an existing
ENUM
definition easily. If you need to modify the allowed values, it may require altering the table structure. - While
ENUM
can enforce data integrity, it may not be as flexible as other data types likeVARCHAR
for storing text data with variable values. - When using
ENUM
, it’s essential to carefully choose the set of values to avoid data inconsistencies.
ENUM
can be useful for columns with a limited set of possible values, such as status indicators, categories, or types, where you want to ensure that only predefined values are allowed in the column.