Answer the question
In order to leave comments, you need to log in
How to find the first free ID in the database?
Good afternoon.
In a DB there is a table in which 2 fields
user_id (autoincrement)
full_name
In the table some millions of records. Data is periodically deleted and added.
At the moment, the task is to, when creating a new user, if possible, give him an id not by auto-increment, but first check for possibly free id.
That is, when creating a user, if there is a free id, for example 325, then give it to him.
The question is how to implement a search for such an ID with a minimum load, since there are several million records in the table.
Common sense tells me that taking and sorting through several million records is, to put it mildly, not an option.
Interested in an elegant solution, at the moment I settled on the following options
SELECT MIN( uid +1 )
FROM `users `
WHERE uid +1 NOT
IN (
SELECT uid
FROM `users`
)
Answer the question
In order to leave comments, you need to log in
> Create a separate table in which I will store free IDs
is the best option.
you don't need it... Well, don't pay attention to the value of the auto-increment field, forget about it...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question