Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question

marked as duplicate by akonsu, noahandthewhale, Igor Romanchenko, mu is too short, Josh Crozier Nov 20 '13 at 4:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
    
@akonsu thank you for leading me in the right direction –  noahandthewhale Nov 19 '13 at 21:28
    
@akonsu I have voted to close this question. –  noahandthewhale Nov 19 '13 at 21:28

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
thanks for the answer, really appreciate it. –  noahandthewhale Nov 19 '13 at 21:28
    
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. –  noahandthewhale Nov 19 '13 at 21:29
    
No worries, it only took a moment. –  Nathan L Nov 19 '13 at 21:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.