Note that using the REPEATABLE READ
isolation level, the default one for InnoDB, you can simply use the SELECT ... FOR UPDATE
syntax, as follows:
Test schema:
CREATE TABLE your_table (id int) ENGINE=INNODB;
INSERT INTO your_table VALUES (1), (2), (3);
Then we can do the following:
START TRANSACTION;
SELECT @x := MAX(id) FROM your_table FOR UPDATE;
+---------------+
| @x := MAX(id) |
+---------------+
| 3 |
+---------------+
1 row in set (0.00 sec)
Without committing the transaction, we start another separate session, and do the same:
START TRANSACTION;
SELECT MAX(id) FROM your_table FOR UPDATE;
The database will wait until the lock set in the previous session is released before running this query.
Therefore switching to the previous session, we can insert the new row and commit the transaction:
INSERT INTO your_table VALUES (@x + 1);
COMMIT;
After the first session commits the transaction, the lock will be lifted, and the query in the second session is returned:
+---------+
| MAX(id) |
+---------+
| 4 |
+---------+
1 row in set (8.19 sec)