What MySQL Returns for Invalid ENUM Values



If strict SQL mode is disabled and we insert an invalid value (which is not in the list of permitted enumeration values) into ENUM, MySQL will insert an empty string instead of throwing an error. If strict SQL mode is enabled, MySQL throws an error when inserting invalid value.

Invalid values without strict SQL mode

Strict SQL mode is disabled by default. When it is disabled, if we enter an invalid value that is not in the ENUM list, it returns an empty string. Let us understand this by using the example below.

Example

In the below example we have a table called Result with a Grade column as ENUM data type and has values 'A', 'B', 'C'. When we insert invalid value into an ENUM column i.e. 'abcd' which is not in ENUM list then empty string will be inserted into 'Result' table.

Creating table

First let us create table with ENUM column. The query is as follow as ?

CREATE TABLE Result (  
    Id INT,  
    Name VARCHAR(50),  
    Grade ENUM('A', 'B', 'C')  
);
Inserting Records

Now, let us see what happens if we insert a invalid string into ENUM, while SQL mode is disabled.

INSERT INTO Result (Id, Name, Grade)
VALUES (100, 'Gaurav', 'abcd');
Verification

By fetching the data we can check whether the invalid string is inserted or not. We use SELECT statement to display the records.

SELECT * FROM Result;

Following is the output of the above query ?

Id Name Grade
100 Gaurav

From the query above, we can see that MySQL has inserted an empty string at the place of invalid string and no error has been thrown because SQL mode is disabled.

Now, with the help of the following query we can get the index number, which is 0 and it confirms that the string inserted by MySQL is an empty string because the index value of empty string is always 0.

SELECT Grade + 0 from Result;

Following is the output of the above query ?

Grade + 0
0

This confirms that the invalid value was replaced with an empty string, having an index of 0.

Invalid values with strict SQL mode

After enabling the SQL strict mode, as done in query below, MySQL throws an error on inserting the invalid string into ENUM.

Set SQL_MODE = 'Traditional';
Inserting Records

Now, insert the same invalid value into the table result ?

INSERT INTO Result(Id, Name, Grade) 
VALUES(101, 'Saurabh','abcd');

Following is the output of the above query ?

ERROR 1265 (01000): Data truncated for column 'Grade' at row 1

In strict mode, MySQL ensures data integrity by rejecting invalid ENUM values and throwing an error.

Conclusion
  • MySQL places an empty string when an ENUM value is invalid in a case where strict SQL mode is disabled.
  • An empty string is indexed with a value of 0.
  • Strict SQL mode prevents invalid values and enforces data integrity.
Updated on: 2025-02-12T12:09:05+05:30

694 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements