views:

72

answers:

3

I have a table with id column. ids are in ascending order but not necessarily consecutive. For example: 1, 2, 3, 5, 6, 10, 11, 12

I need to find the next "free" id, i.e. max(id) + 1 (or 1 if the table is empty).

Currently I'm doing this in PHP like this:

function get_free_id($con) {
    $sql = "SELECT MAX(id) AS last_id FROM Table";
    $last_id_query = mysql_query($sql, $con);
    $last_id_result = mysql_fetch_array($last_id_query);
    $last_id = $last_id_result['last_id'];  
    return ($last_id == NULL) ? 1 : ($last_id + 1);
}

I have a feeling that this function is "too long" for this simple task and that this can be done much simpler.

Am I right ? How ?

+6  A: 

There is no guaranteed way.
So, you shouldn't do it that way.

Create a record first, get autogenerated id and then use it where you wanted it.

Col. Shrapnel
What do you mean by "There is no guaranteed way." ?
Misha Moroshko
+1  A: 

does auto_increment help?

http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Kent
If I use AUTO_INCREMENT id, insert a couple of rows, and then close the connection. At later time, how would I get the next free id ? (say I need it for other purposes, not for the next INSERT) Should I save it from the last time I inserted a row ?
Misha Moroshko
+2  A: 

The issue you will have in doing this way is when you have concurrent requests for the next ID. Two records could potentially end up requesting the same ID and then one will fail when you try to insert it. That being said, if you really want to do it this way, here are a couple of options.

// select the id to use for your insert statement
SELECT coalesce(max(id)+1,1) AS ID FROM `table`;

// select next value during insert
INSERT INTO `table`(id,name)
    SELECT coalesce(max(id)+1,1) AS ID, 'New Name' FROM `table`

That being said, I would advise against doing it this way. But here you have your answer.

cdburgess
I really need to think about concurrent requests...Anyway, my main question was how to get the number **in PHP**...
Misha Moroshko
Also, do AUTO_INCREMENT solve the concurrency problem ?
Misha Moroshko