Does INSERT IGNORE lock the table even if it ignores the insert?

前端 未结 1 848
长发绾君心
长发绾君心 2021-01-28 10:42

In MySQL, If I have an INSERT IGNORE command that eventually doesn\'t insert into the table, due to the uniqueness constraint. Does it ask and wait for a write lock? Or does MyS

相关标签:
1条回答
  • 2021-01-28 11:06

    It depends on the engine - MyIsam and InnoDb behave diferrently.

    For MyIsam tables, if a record already exist in the table (even if it is not commited yet), a regular INSERT of the same record (the same unique key) in the other session reports a duplctate key error - so INSERT IGNORE just ignores the error and proceed further.

    On InnoDB table, if the record is not locked, the regular INSERT will immediately report the duplicate key error (INSERT IGNORE will skip the error and go on).
    But if the record is locked by the other session (for example the record is inserted but not commited yet, or the record is locked by an UPDATE or DELETE or SELECT FOR UPDATE command), the INSERT command will "hang" and will be waiting until the other session will remove the lock (by COMMIT or ROLLBACK). Then, if record still exists after removing the lock, INSERT will report the error (INSERT IGNORE will ignore the error), but if record doesn't exist, INSERT will add this record to the table.

    IGNORE keyword just says "in case of any error just ignore it an go on", but it doesn't affect locking behaviour.

    0 讨论(0)
提交回复
热议问题