I want to insert row with unique value in non-primary key field. I cannot use unique index (because of NULL values in multiple field index, but it is not important here).
I use INSERT/SELECT WHERE NOT EXISTS as an atomic (I hope) operation - see below.
I will describe problem on simplified example:
I have an empty table:
CREATE TABLE Test (
Id int(11) NOT NULL AUTO_INCREMENT,
A int(11) DEFAULT NULL,
PRIMARY KEY (Id)
) ENGINE=InnoDB;
... and 2 sessions with autocommit mode switched off:
In first session I execute:
INSERT INTO Test (A)
SELECT A FROM (SELECT 1 AS A) Inn
WHERE NOT EXISTS (SELECT A FROM Test WHERE A = 1 FOR UPDATE);
In second session I execute:
INSERT INTO Test (A)
SELECT A FROM (SELECT 2 AS A) Inn
WHERE NOT EXISTS (SELECT A FROM Test WHERE A = 2 FOR UPDATE);
As you can see, I'm inserting independent values. But this second session is locked by the first one. Why? Maybe it is because of gap/next-key lock.
How else i can insert records with "manual" avoiding of duplicate keys and without mutual locking?
Default transaction isolation level is REPEATABLE READ and I don't want to change default settings of database, because other applications use it.