MySQL INSERT IGNORE Statement Explained?
Summary: in this tutorial, you will learn how to use the MySQL INSERT IGNORE statement to insert data into a table.
Introduction to MySQL INSERT IGNORE statement
When you use the
INSERT
statement to add some rows to a table and if an error occurs during the processing, MySQL will abort the INSERT
statement and return an error. As the result, no rows are inserted into the table.
However, if you use the
INSERT IGNORE
statement, the rows that cause the errors are ignored and the remaining rows are inserted into the table.
The syntax of the
INSERT IGNORE
statement is as follows:
Note that the
IGNORE
clause is an extension of MySQL to the SQL standard.MySQL INSERT IGNORE example
We will create a new table called
subscribers
for the demonstration.
The
UNIQUE
constraint ensures that no duplicate email exists in the email
column.
The following statement inserts a new row into the
subscribers
table:
It worked as expected.
Let’s execute another statement that inserts two rows into the
subscribers
table:
It returns an error.
As indicated in the error message, the email
john.doe@gmail.com
violates the UNIQUE
constraint.
However, if you use the
INSERT IGNORE
statement instead.
MySQL returned a message indicating that one row was inserted and the other row was ignored.
To find the detail of the warning, you can use the
SHOW WARNINGS
command as shown below:
In conclusion, when you use the
INSERT IGNORE
statement, instead of issuing an error, MySQL issued a warning in case an error occurs.
If you query data from
subscribers
table, you will find that only one row was actually inserted and the row that causes the error was not.MySQL INSERT IGNORE and STRICT Mode
When the strict mode is on, MySQL returns an error and aborts the
INSERT
statement if you try to insert invalid values into a table.
However, if you use the
INSERT IGNORE
statement, MySQL will issue a warning instead of an error. In addition, it will try to adjust the values to make them valid before adding the value to the table.
Consider the following example.
First, we create a new table named
tokens
:
In this table, the column
s
accepts only string whose lengths are less than or equal to six.
Second, insert a string whose length is seven into the
tokens
table.
MySQL issued the following error because the strict mode is on.
Third, use the
INSERT IGNORE
statement to insert the same string.
MySQL truncated data before inserting it into the
tokens
table. In addition, it issues a warning.
In this tutorial, you have learned how to use the MySQL
INSERT IGNORE
statement to insert rows into a table and ignore error for rows that cause errors.
0 comments:
Post a Comment