Skip to content
On this page

📆 2019-03-01

Generate Secquence in MySQL without LOCK or Transaction

#MySQL

MySQL supports to generate sequence by LAST_INSERT_ID.

According to the document, there is no need to use lock or transaction:

This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. https://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id

First, create table for sequence, and insert row to persistant currenct sequence number. like this:

mysql> CREATE TABLE my_sequence (id UNSIGNED BIGINT NOT NULL);
mysql> INSERT INTO my_sequence VALUES (0);

Then, We can generate sequence:

mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql> SELECT LAST_INSERT_ID();

Released under the MIT License.