
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
Enum with Not Null in a MySQL Field
In MySQL, the ENUM is a data type that is used to create a column with a fixed set of values. It is helpful for the fields that have limited alternatives, such as categories, statuses, and color codes.
In the ENUM data type, if you do not declare NOT NULL then it gives the default value NULL or Empty String('') when inserting records without specifying a value. However, if you declare NOT NULL and don't specify the values when inserting then it gives the first value from the ENUM. Following is the syntax to create a table that has a column as ENUM data type.
CREATE TABLE table_name ( column_name ENUM('value1', 'value2', ..., 'valueN') );
Case 1: Without NOT NULL
In this case, when an ENUM column is not declared as NOT NULL, MySQL will allow NULL values into the table if no specific value is inserted. Let us first create a table When the ENUM gives NULL value:
CREATE TABLE DemoTable1 ( isMarried ENUM('YES', 'NO') );Inserting Records
Insert sample data in the table using INSERT command ?
INSERT INTO DemoTable1 values();Verification
Display all records from the table using SELECT statement ?
SELECT * FROM DemoTable1;
Following is the output of the above query ?
isMarried |
---|
NULL |
Since no value is inserted MySQL will provide NULL by default in the isMarried column.
CASE 2: With NOT NULL
When NOT NULL is declared in an ENUM field, MySQL will not allow NULL. If no value is specified during insertion, MySQL will automatically assign the first defined value from the ENUM list.
Let us create a table where the ENUM gives the first value from ENUM:
CREATE TABLE DemoTable1 ( isMarried ENUM('YES', 'NO') NOT NULL );Inserting Records
Insert some records in the table using INSERT command ?
INSERT INTO DemoTable2 values();Verification
Display all records from the table using SELECT statement ?
SELECT * FROM DemoTable2;
Following is the output of the above query ?
isMarried |
---|
YES |
In a NOT NULL ENUM field, the first ENUM option(YES) is inserted when no specific value is provided. From the above cases, I would like to conclude that the ?
ENUM without NOT NULL: If no value is declared by default it gives NULL.
ENUM with NOT NULL: When no value is given, the first ENUM value is declared by default.