Search code examples
mysqlauto-increment

How can I update an existing record to have a new auto_increment id in MySQL?


I have a table with primary key (its name is "id") defined as auto_increment. I use NULL in INSERT statements to "fill" the id value. It works, of course. However now I need to "move" an existing record to a new primary key value (the next available, the value is not so much important, but it must be a new one, and the last one if ordered by id). How can I do it in an "elegant" way? Since the "use NULL at INSERT" does not work too much with UPDATE:

update idtest set id=NULL where id=1;

This simply makes the id of the record zero. I would expect to do the same thing as with INSERT, but it seems my idea was incorrect.

Of course I can use "INSERT ... SELECT" statement, then a DELETE on the old one, or I can use something like MAX(id) + 1 to UPDATE the id of the old record in one step, etc, but I am curious if there is a finer solution.

Also, the MAX(id) solution doesn't seem to work either by the way:

mysql> update idtest set id=max(id)+1 where id=3;
ERROR 1111 (HY000): Invalid use of group function
mysql> update idtest set id=(select max(id)+1 from idtest) where id=3;
ERROR 1093 (HY000): You can't specify target table 'idtest' for update in FROM clause

Solution

  • The way you are trying to update same table is wrong but you can use join on same table

    update idtest t
    join (select id +1 as id
        from idtest order by id desc 
        limit 1) t1
    set t.id=t1.id
    where t.id=3;
    

    or

    update idtest t
    join (select max(id) +1 as id
        from idtest ) t1
    set t.id=t1.id
    where t.id=3;