Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle fragmentation of auto_increment ID column in MySQL

I have a table with an auto_increment field and sometimes rows get deleted so auto_increment leaves gaps. Is there any way to avoid this or if not, at the very least, how to write an SQL query that:

  1. Alters the auto_increment value to be the max(current value) + 1
  2. Return the new auto_increment value?

I know how to write part 1 and 2 but can I put them in the same query?

If that is not possible:

How do I "select" (return) the auto_increment value or auto_increment value + 1?

like image 686
Stuart Avatar asked Dec 29 '22 09:12

Stuart


1 Answers

Renumbering will cause confusion. Existing reports will refer to record 99, and yet if the system renumbers it may renumber that record to 98, now all reports (and populated UIs) are wrong. Once you allocate a unique ID it's got to stay fixed.

Using ID fields for anything other than simple unique numbering is going to be problematic. Having a requirement for "no gaps" is simply inconsistent with the requirement to be able to delete. Perhaps you could mark records as deleted rather than delete them. Then there are truly no gaps. Say you are producing numbered invoices: you would have a zero value cancelled invoice with that number rather than delete it.

like image 195
djna Avatar answered Apr 07 '23 15:04

djna