In my db application I have a requirement for a unique, 4-digit number field for each customer. Up until 9999 I can just use autoincrements, but after that I will have to reuse numbers of customers that have been deleted (there won’t be more than 5000 customers at a given time but there may be more than 9999 customers over the lifetime of the system).
Question 1: Is there a (My)SQL statement to find the next reusable free number?
Question 2: If I get the number, assign it to a new customer and save the customer all in one transaction, similar transactions taking place at the same time will be sequentialized by the database so the numbers won’t collide, right?
You’d be better off storing a table with all 10,000 possible values defined, and an “in-use” flag on each. That way, releasing the number for re-use is a simple update to set “inuse=false”.
Also makes finding the lowest available value a simple
Doing that with appropriate locks/transactions would prevent two or more requests getting the same ID, and since it’s a small table, doing a global table lock would not significantly impact performance.
Otherwise, you’d be stuck rummaging around your users table, trying to find the first “gap” in the numbering sequence.