What Happens to Auto-Increment IDs When You Delete a Row
A question I hear from almost every beginner: "I deleted row 3, and now my ids go 1, 2, 4, 5. How do I fix it?" The short answer is that nothing is broken. This post explains why the gap appears and why you should leave it alone.
Seeing it happen
In SQLite:
CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
INSERT INTO pets (name) VALUES ('Rex'), ('Mia'), ('Bo');
DELETE FROM pets WHERE id = 2;
INSERT INTO pets (name) VALUES ('Lu');
SELECT * FROM pets;
You will see ids 1, 3 and 4. Mia's number, 2, is not given to Lu.
(A small SQLite detail: with plain INTEGER PRIMARY KEY, SQLite normally picks one more than the current largest id, so deleting the *last* row can let its number come back. Adding the AUTOINCREMENT keyword guarantees numbers are never reused. Other databases, such as PostgreSQL with identity columns and MySQL with AUTO_INCREMENT, do not reuse deleted numbers in normal use.)
Why databases do not fill gaps
An id is a name, not a position. The id 3 means "Bo", not "the third pet". If the database renumbered Bo to 2 after Mia left, anything that remembered "pet 3", such as a link in an email, a bookmark or another table, would now point at the wrong pet, or at nothing.
Other tables depend on it. If a vet_visits table has pet_id = 3, renumbering Bo would break that link. Foreign keys only work because primary keys stay put.
Speed and simplicity. Handing out "the next number" is quick and safe even when many users insert at once. Searching for the smallest free gap would be slow and complicated.
Other ways gaps appear
Gaps are normal for several reasons besides deletes:
- An insert that fails or is rolled back may still use up a number.
- Some databases reserve numbers in batches for speed.
- Restarts can skip numbers in certain engines.
So you should never expect ids to be continuous.
"But I want a neat 1, 2, 3 list"
That is a display question, not a storage question. Number rows when you show them:
SELECT ROW_NUMBER() OVER (ORDER BY name) AS position, name
FROM pets;
ROW_NUMBER() is a window function, supported in SQLite since version 3.25.0 and in PostgreSQL, MySQL 8.0 and SQL Server. Or simply count in your program while printing.
Summary
| Belief | Reality |
|---|---|
| Gaps mean something went wrong | Gaps are normal |
| I should renumber my ids | Renumbering breaks links |
| Ids show how many rows there are | Use COUNT(*) for that |
| I need tidy numbers for display | Number rows in the query or in code |
The habit to keep
Treat ids as labels you never change. Our follow-up questions about primary keys cover more of these rules.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.