INSERT IGNORE Clause For MySQL
If you want to insert rows from a SELECT
query into another table, ensuring that unique rows are inserted (based on the unique constraints of the target table), you can use the INSERT IGNORE
statement. The INSERT IGNORE
the command will insert rows from the SELECT query into the target table, but if a row causes a duplicate entry for a primary key or unique index, MySQL will ignore the error and continue with the next row.
Here’s the general syntax:
INSERT IGNORE INTO target_table (column1, column2, ...)
SELECT column1, column2, ...
FROM source_table
WHERE some_conditions;
For example, let’s say you have a source_table
with columns id
, name
, and age
, and a target_table
with the same columns. If you want to insert rows from source_table
into target_table
ensuring unique rows based on the id column are inserted, you would do the following:
INSERT IGNORE INTO target_table (id, name, age)
SELECT id, name, age
FROM source_table;
With INSERT IGNORE
, if a row from the SELECT
query would result in a “duplicate key” error in the target_table
, that row will be skipped, and the insert will proceed with the next row.