Search code examples
mysqlsqluniquesql-insert

Unique VS INSERT IGNORE


As you know, unique columns only accept non-repetitive values. Now, I saw a keyword named IGNORE (It is used after INSERT statement).

Well, I read about INSERT IGNORE in the documentation and I figured out its job is exactly what unique does! So, when should I use IGNORE instead of unique column? When it is useful?


Solution

  • These two constructs are complimentary. A unique constraint makes sure a column cannot get repetitive values. The ignore keyword in an insert statement allows the insert statement to ignore any errors (such as unique constraint violations) when inserting new rows to a table.

    Without the constraint, your insert statement would just create repetitive values in the table. Without the ignore keyword, attempting to insert such values would error out instead of just silently doing nothing.