6

I'm trying to figure out why Django (or PostgreSQL, not to sure at which level it is) doesn't reuse primary keys from objects that have been deleted. When objects are created, they all have an id value that is auto incremented and ordered by the id value in the database. For example:

ID

5

4

3

2

1

Let's say I happen to delete the object with an ID of 5:

ID

4

3

2

1

When I create a new object, it has an ID of 6:

ID

6

4

3

2

1

Why wasn't "5" assigned as the primary key to the new object I just created? Why does it have 6 instead?

3
  • 1
    stackoverflow.com/questions/9984196/… Commented Nov 19, 2013 at 21:23
  • @akonsu thank you for leading me in the right direction Commented Nov 19, 2013 at 21:28
  • @akonsu I have voted to close this question. Commented Nov 19, 2013 at 21:28

1 Answer 1

17

The primary key assigned is often based on a sequence because it's easier to store and calculate a single value and the next value in the sequence. Consider a table with 1 million records and a delete that removes 50 thousand of those records. To fill in the newly opened key values you either have to use memory to store those options or scan the table for the lowest open value. Both are expensive compared to just assigning the next value in the sequence.

Sign up to request clarification or add additional context in comments.

2 Comments

I have voted to close this question since akonsu has pointed out there is a duplicate. Thank you for taking the time to answer this.
No worries, it only took a moment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.