I have a sequence used to seed my (Integer based) primary keys in an oracle table.
It appears this sequence has not always been used to insert new values into the table. How do I get the sequence back in step with the actual values in the table?
I have a sequence used to seed my (Integer based) primary keys in an oracle table.
It appears this sequence has not always been used to insert new values into the table. How do I get the sequence back in step with the actual values in the table?
In short, game it:
-- Current sequence value is 1000
ALTER SEQUENCE x INCREMENT BY -999;
Sequence altered.
SELECT X.NEXTVAL FROM DUAL;
1
ALTER SEQUENCE x INCREMENT BY 1;
Sequence altered.
You can get the max sequence value used within your table, do the math, and update the sequence accordingly.
If ID is the name of your PK column and PK_SEQ is the name of your sequence:
Find the value of the highest PK by SELECT MAX(ID) FROM tableName
Find the value of the next PK_SEQ by SELECT PK_SEQ.NEXTVAL FROM DUAL
Bump the sequence by SELECT PK_SEQ.NEXTVAL FROM DUAL
Reset the sequence increment value to 1 by ALTER SEQUENCE PK_SEQ INCREMENT BY 1
This all assumes that you don't have new inserts into the table while you're doing this...
In some cases, you may find it easier to simply get the current max value and then
drop sequence x;
create sequence x start with {current max + 1};
The app will be broken after you do the drop. But that will keep anybody from inserting rows during that period, and creating a sequence is quick. Make sure you recreate any grants on the sequence since those will be dropped when the sequence is. And you may want to manually recompile any plsql that depends on the sequence.