Open In App

Enumerator (Enum) in MySQL

An ENUM is a string object whose value is decided from a set of permitted literals(Values) that are explicitly defined at the time of column creation.

Benefits of Enum data type –



Enum syntax for columns :

CREATE TABLE table_name (
  col...
  col ENUM ('value_1','value_2','value_3', ....),
  col...
);

MySQL allows us to define the ENUM data type with the following three attributes  –



Example :
Suppose, we want to store the student data in the table Student_grade in order to store the grades of students in the corresponding columns (High, Medium, Low). We use the priority statement to assign the priority to the Enum column.

CREATE TABLE Student_grade(
id INT PRIMARY KEY AUTO_INCREMENT, Grade VARCHAR(250) NOT NULL,
priority ENUM('Low', 'Medium', 'High') NOT NULL
);

The prioritized column will accept only three columns. Here, the order of numbering Low->1, Medium->2, High->3.

Insert data into the table –

INSERT INTO Student_grade(Grade, priority)
VALUES('Good grades', 'High');
INSERT INTO Student_grade(Grade, priority)
VALUES('Poor grades', 1);
// Here we use 1 instead of using 'Low' enumeration value, 
since 1 is mapped to 'Low' implicitly.
INSERT INTO Student_grade(Grade, priority)
VALUES('Mediocre grade', 'Medium');

INSERT INTO Student_grade(Grade)
VALUES('Poor grades',1);

INSERT INTO Student_grade(Grade)
VALUES('Good grades','High');

Note : ENUM column can also store NULL values if it is defined as a null-able column.

Output :

SELECT * FROM Student_grade
WHERE priority = 'High';
SELECT * FROM Student_grade
WHERE priority = 3;

SELECT Grade, priority FROM Student_grade
ORDER BY priority DESC;

Sort_data

MySQL ENUM Disadvantages :
 

SELECT colmn_type FROM inform_schema 
WHERE TABLE_NAME = 'Student_grade' AND COLUMN_NAME = 'priority';

 

Article Tags :
SQL