For some reason, people in the past have inserted data without using sequence.NEXTVAL. So when I go to use sequence.NEXTVAL in order to populate a table, I get a PK violation, since that number is already in use in the table.
How can I update the next value so that it is usable? Right now, I'm just inserting over and over until it's successful (INSERT INTO tbl (pk) VALUES (sequence.NEXTVAL)
), and that syncs up the nextval.
You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example
ALTER SEQUENCE mysequence INCREMENT BY 100; select mysequence.nextval from dual; ALTER SEQUENCE mysequence INCREMENT BY 1;
In my case I have a sequence called PS_LOG_SEQ
which had a LAST_NUMBER = 3920
.
I then imported some data from PROD
to my local machine and inserted into the PS_LOG
table. Production data had more than 20000
rows with the latest LOG_ID (primary key) being 20070. After importing I tried to insert new rows in this table but when saving I got an exception like this one:
ORA-00001: unique constraint (LOG.PS_LOG_PK) violated
Surely this has to do with the Sequence PS_LOG_SEQ
associated with the PS_LOG
table. The LAST_NUMBER
was colliding with data I imported which had already used the next ID value from the PS_LOG_SEQ
.
To solve that I used this command to update the sequence to the latest \ max(LOG_ID)
+ 1:
alter sequence PS_LOG_SEQ restart start with 20071;
This command reset the LAST_NUMBER
value and I could then insert new rows into the table. No more collision. :)
Note: this alter sequence
command is new in Oracle 12c.
Note: this blog post
documents the ALTER SEQUENCE RESTART option does exist, but as of 18c, is not documented. Its apparently intended for internal Oracle use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With