Search code examples
sqlprimary-keyauto-incrementrelation

Modifying id values in a relation automatically


I have a question regarding DB. Lets say I have id column which is primary key. And 4 rows. Once i remove the row 0 the 1st row must become row 0 in that table. once you set table ID as auto_increment, does it do that trick? Best regards


Solution

  • Succinctly, No.

    That is, once an auto increment column is assigned a value, it stays with the assigned value in perpetuity.

    Think about it; suppose you have a table with a million and one rows in it. If you delete the row with ID 0 and then want to renumber the remaining rows, not only do you have to update each and every one of the remaining million rows, you also have to cascade those updates to the referencing foreign keys in other tables. You've just demanded a rewrite of a significant portion of the database. Which is bad for concurrency, and log file usage, and just about everything else (every report that mentioned the ID number for a still existing row is obsolete). Think what would happen to you if your bank account number changed any time someone else closed their account!

    Filling in gaps like you seem to be asking about is usually not necessary.