2

currently I'm using postgresql as my database and I import all the data into the table through MS Excel csv format. All things went out smoothly but the problem is whenever I want to insert additional data into the table for example using the following code:

insert into country (name)
values ('America');

it keeps pop up an error of

ERROR:  duplicate key value violates unique constraint "effect_pkey"
DETAIL:  Key (country_id)=(1) already exists.
********** Error **********

ERROR: duplicate key value violates unique constraint "effect_pkey"
SQL state: 23505
Detail: Key (country_id)=(1) already exists.

when I keep trying to insert the data, the error getting is similar just the country_id in the error message is increasing. then I can only insert the data when I surpass the existing ID in my table. I would like to know how can I solve this out. Thank you very much.

6
  • Please add the table definition for the country table to your question. (country_id is a serial?) Commented Mar 4, 2014 at 9:38
  • @joop ya the id is in serial format and it's just a simple table with ID and NAME, Commented Mar 4, 2014 at 9:38
  • Than probably your data import forgot to reset the serial (to the maximal occuring value in the table) Commented Mar 4, 2014 at 9:40
  • @joop how should I overcome this issue..hmmmm Commented Mar 4, 2014 at 9:41
  • You have to reset your primary serial key to the current value+1 imported from your file: You can chieve this like this: stackoverflow.com/a/3819323/1216680 Commented Mar 4, 2014 at 9:44

2 Answers 2

2

Something like:

SELECT setval('country_id_seq', (SELECT MAX(country_id) FROM country) );

(I don't know the exact names, since the OP did not give a table definition in his question)

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

Comments

0

A better solution now might be to use GENERATED AS IDENTITY to allow PostgreSQL to assign the id while ensuring it's not ever assigned externally.

See for example https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-identity-column/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.