Lock the table, find out the first available ID, insert all your stuff related to the ID, and then unlock the table. The locking is to avoid concurrent modifications and hence duplicate IDs. You won't encounter the problem unless you are making a lot of queries each second.