You can use LEFT JOIN to find minimum unused value in a MySQL table. Let us first create a table
mysql> create table FindValue -> ( -> SequenceNumber int -> ); Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into FindValue values(109); Query OK, 1 row affected (0.14 sec) mysql> insert into FindValue values(110); Query OK, 1 row affected (0.15 sec) mysql> insert into FindValue values(111); Query OK, 1 row affected (0.13 sec) mysql> insert into FindValue values(113); Query OK, 1 row affected (0.13 sec) mysql> insert into FindValue values(114); Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from FindValue;
The following is the output
+----------------+ | SequenceNumber | +----------------+ | 109 | | 110 | | 111 | | 113 | | 114 | +----------------+ 5 rows in set (0.00 sec)
Here is the query to find minimum unused value in a MySQL table
mysql> select tbl1 .SequenceNumber+1 AS ValueNotUsedInSequenceNumber -> from FindValue AS tbl1 -> left join FindValue AS tbl2 ON tbl1.SequenceNumber+1 = tbl2.SequenceNumber -> WHERE tbl2.SequenceNumber IS NULL -> ORDER BY tbl1.SequenceNumber LIMIT 1;
The following is the output
+------------------------------+ | ValueNotUsedInSequenceNumber | +------------------------------+ | 112 | +------------------------------+ 1 row in set (0.00 sec)