tags:

views:

58

answers:

1

Say I have a table with a unique positive integer field. I currently have rows with id's of [1, 2, 3, 4, 5, 8, 12, 35]. Is there a insert query that I could write that would assign the id field to the lowest unique positive integer (in this case 6)? It would have to do this atomically so there isn't the possibility of concurrent inserts wiping out each other or failing.

+1  A: 

I would not use this to fill up "missing" ids, but this should work:

Insert Into t (id)
  Select Coalesce( Min(t.id) + 1, 0 )
  From t
  Left Join t As t2 On ( t2.id = t.id + 1 )
  Where t2.id Is Null

Get all ids where id + 1 does not exist (Left Join), and insert Min(id)+1 or 0 if non is available.

Peter Lang