I'm not sure how efficient it would be, and it probably depends on what your database is, but you could perhaps find the minimum number by a single database query by joining a sequence generation and returning the lowest value of the sequence which is not a table index.
A Monk aims to give answers to those who have none, and to learn from those who know more.