ENUM in MySQL
In MySQL, ENUM is a datatype that allows you to create a set of predefined values. The ENUM data type allows you to specify a list of values that a column is allowed to have. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of ENUM in MySQL.
Syntax
The syntax for defining an ENUM column is as follows:
column_name ENUM('value1', 'value2', ... 'valueN')
Where column_name
is the name of the column, and value1
, value2
, and valueN
are the allowed values for the column.
Example
Let's say we want to create a table called "users" with an ENUM column called "gender" that can have the values "Male", "Female", or "Not specified". Here's how we can implement it:
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
gender ENUM('Male', 'Female', 'Not specified')
);
Now, we can insert values into the table:
INSERT INTO users (id, name, gender) VALUES (1, 'John', 'Male');
INSERT INTO users (id, name, gender) VALUES (2, 'Jane', 'Female');
INSERT INTO users (id, name, gender) VALUES (3, 'Bob', 'Not specified');
Output
When we run the example code above, we can select all the values from the table:
SELECT * FROM users;
which would give us the following output:
+----+------+-----------------+
| id | name | gender |
+----+------+-----------------+
| 1 | John | Male |
| 2 | Jane | Female |
| 3 | Bob | Not specified |
+----+------+-----------------+
Explanation
In the example above, we created a table called "users" with an ENUM column called "gender" that can have the values "Male", "Female", or "Not specified". We then inserted three rows into the table, each with a different value for the "gender" column.
Use
ENUM is useful when you have a predefined set of values that a column can have. Instead of allowing any value, you can use ENUM to restrict the allowed values to a set of specific values.
Important Points
- ENUM is a datatype that allows you to create a set of predefined values.
- The values of an ENUM start at 1 and increase by 1 for each allowed value.
- You can use quoted or unquoted values when defining an ENUM.
Summary
In this tutorial, we discussed the syntax, example, output, explanation, use, and important points of ENUM in MySQL. With this knowledge, you can now use ENUM in your MySQL database to restrict the allowed values of a column to a specific set of predefined values.