1

I tried to insert name into database.

name = 'test'
cur.execute("INSERT INTO scholars(name) VALUES('{}') returning id".format(name))
id = cur.fetchone()
print(id)

error message:

psycopg2.IntegrityError: duplicate key value violates unique constraint "idx_16514_primary"
DETAIL:  Key (id)=(2321) already exists.

When id=2301, it succeed,and return ID. After that,id += 1and returns the error below.

http://ob9j09f06.bkt.clouddn.com/2016-10-12-16%3A31%3A12.jpg

2
  • Did you insert values manually without updating the sequence properly? Commented Oct 12, 2016 at 12:10
  • There might be something wrong with your id sequence, run SELECT currval(pg_get_serial_sequence('scholars', 'id')); to show the most recent value created by id sequence. Commented Oct 12, 2016 at 12:18

2 Answers 2

1

Seems to me that You already have record with ID 2321 in your DB. Can You check with SELECT id FROM scholars?

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

2 Comments

But it should be manually add id when i insert a new data.
My guess: You have deleted some records, or You have manually created some IDs, so automatic generator got into problems.
0

Thanks @e4c5, @kxxoling

Here i got the answer How to reset postgres' primary key sequence when it falls out of sync? to this question.

Something was wrong with my id sequence.

I fixed it by doing this.

SELECT MAX(id) FROM scholars;

=> 11518

SELECT nextval('scholars_id_seq');

=> 2324 # here it is lower than max(id)

SELECT setval('scholars_id_seq', (SELECT MAX(id) FROM scholars));

=> 11518 # fix it

SELECT nextval('scholars_id_seq');

=> 11519 # normal

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.