0

I have a table 'new_table' with sequence id as primary key. how can I insert new records to it with data from other table. I tried:

insert into new_table ( 
(select (select NEXTVAL('my_sequence')),a,b,c from old_table)
);

but got

duplicate key value violates unique constraint DETAIL: Key (id)=(...) already exists.

4
  • First, check to see what you are actually getting back from the sequence object ( run this part : select NEXTVAL('my_sequence'). Your Sequence and your table my have gotten out of sequence resulting in a conflict. Commented Feb 8, 2017 at 13:29
  • Second, isolate your sequence selection its own selection statement, putting it into a variable, then using that variable within the insert statement. It will be easier for debugging, and for future maintenance. Commented Feb 8, 2017 at 13:32
  • TNX Maybe you can write an example ? Commented Feb 8, 2017 at 13:50
  • Just omit the sequence :insert into new_table ( a, b, c) select a,b,c from old_table; Commented Feb 8, 2017 at 13:54

1 Answer 1

0
  1. just list columns skipping the one with sequence, smth like:

    insert into new_table (a,b,c) select a,b,c from old_table;

If default value is set to get nextval, you don't have to do it manually.

  1. check if your sequence is not behind the max(id) value. smth like:

select max(id) from new_table

if it is, restart sequence with new cellar, smth like:

alter sequence my_sequence restart with 1999; or what your maximum is

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

2 Comments

You can combine the check the setting of the new value using select setval('my_sequence', (select max(id) from new_table))
should I add this to answer? I thought to put it as simple as possible

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.