
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Avoid Storing Numbers in MySQL ENUM Column
MySQL stores ENUM values internally as integer keys (index numbers) to reference ENUM members. The main reason for not storing the integer values in the ENUM column is that it is very obvious that MySQL ends up referencing the index instead of the value and vice-versa.
These indexes begin at 1, not 0, and map to the order of the values defined during table creation. If a number is inserted directly into an ENUM column, MySQL interprets it as the corresponding index, leading to unexpected behavior.
Example
Let us create a table named Enmtest with a Status column as ENUM data type with pre-defined numeric values.
CREATE TABLE Enmtest( Status ENUM('0', '1', '2') );
Now, let us populate the table with the pre-defined value which is in string type, and another value as numeric into the ENUM column.
INSERT INTO Enmtest values('1'),(1);
Let us fetch the data we have inserted using the SELECT statement.
SELECT * FROM Enmtest;
Following is the output of the above query ?
Status |
---|
1 |
0 |
Here, we inserted ?1' as a string and accidentally also inserted 1 as a number (without quotes). MySQL confusingly uses our number input as an index value i.e. an internal reference to the first item in the member list (i.e. 0).
Example 2
Let us create a table named Task with an ENUM column named Status, which has predefined values: pending, completed, and failed. The column is assigned a default value of pending, ensuring that if no value is provided during insertion, the status will automatically be set to pending.
CREATE TABLE Task ( Status ENUM('pending', 'completed', 'failed') DEFAULT 'pending' );
Now, let us populate the table with the data which is pre-defined that is string values and a numeric value.
INSERT INTO Task VALUES ('completed'), (3);
To display the records we use the SELECT statement.
SELECT * FROM Task;
Following is the output of the above query ?
Status |
---|
completed |
failed |
Here, 'completed' (string) matches the ENUM definition and is stored as it is and 3 (number) is treated as the index, which maps to 'failed', the second value in the ENUM list.