How Many B+Tree Searches Are Hidden Inside a MySQL Insert?

image-1

2️⃣ Number of B+Tree Searches When Inserting into a Primary Key Index

➔ Maximum number of B+Tree searches: 5 + (B+Tree height - 2)

3️⃣ Number of B+Tree Searches When Inserting into a Unique Secondary Index

➔ Maximum number of B+Tree searches: 6 + (B+Tree height - 2)

💡Additional Note on the 2nd Search for Unique Secondary Index Insertions

Some might wonder: why is a second search necessary to check for duplicates? Why can’t we verify duplicates directly during the first search?

The reason is that, unlike the primary key index, secondary indexes in InnoDB do not perform in-place updates. Instead, updates are handled by marking the old record as deleted (delete mark) and inserting a new record. As a result, even for a unique secondary index, there may be multiple records internally with the same indexed column values. The position where the first search stops might not point to a valid, active duplicate entry — it could be a delete-marked record — while the real active record might be located elsewhere. Therefore, a second search is needed, starting from the leftmost potential duplicate, to scan and validate whether a true duplicate exists.

💡A Potential Optimization Idea I Can Think Of:

If the first search already stops at a valid (non-delete-marked) duplicate entry, it might be possible to directly acquire the necessary locks and return a duplicate key error, without requiring a second full search. This could potentially reduce some overhead in certain cases.