I have a PHP page which interacts with this small MySQL database table with a simple structure. ID, Name, Address are the fields. ID is the primary key.
+------+------------+-------------+
| ID | Name | Country |
|______|____________|_____________|
| E001 | Stephen | America |
| E002 | John | Britain |
| E003 | Kate | Canada |
| E004 | Carlos | Spain |
| E005 | James | Australia |
|______|____________|_____________|
If I remove the record at E003, it looks like this.
+------+------------+-------------+
| ID | Name | Country |
|______|____________|_____________|
| E001 | Stephen | America |
| E002 | John | Britain |
| E004 | Carlos | Spain |
| E005 | James | Australia |
|______|____________|_____________|
A gap appears between E002 and E004.
Is there a way to fill in that gap? Like this
+------+------------+-------------+
| ID | Name | Country |
|______|____________|_____________|
| E001 | Stephen | America |
| E002 | John | Britain |
| E003 | Carlos | Spain |
| E004 | James | Australia |
|______|____________|_____________|
Earlier record which had E004, fall into the place of E003. Former E005 gets the number E004 and so on. Like the records take a step back.
Is there a way to do this programmatically?
Is there a reason you need to renumber them? The key values shouldn’t really matter. If they do (i.e., they are used for outside purposes), consider having the external key be a regular column in the table and let the primary key be an auto-increment integer field. Even if you do this, you still probably shouldn’t be renumbering keys. That would mean that all external dependencies would need to be updated as well. There’s just not much value in doing it.
But, if you have to…
If the key is auto-increment (which it should be), you can do this:
If it’s not, then you can do several things, but the easiest might be to use variables to act as a counter. To make this easier, please don’t use a string primary key, but instead use a plain numeric primary key.