Friday, August 05, 2011

Reset 'Next Value' of an Oracle sequence

In all RDBMS's, the power of sequences is just priceless. This is also true for Oracle...Sometime we happen to need to reset the next value of a sequence and unfortunately there is no single line command to do it in Oracle. This article show the basic steps to reset the next or current values of an Oracle sequence.

Let's say that we have a sequence 'my_sequence' (pretty original huh?) whose nextval is 900000:

select my_sequence.nextval from dual;

> 900000

However we discover that after deleting some data from a table, we realize that we need to reset the sequence so that the next value is 400000. This can be done in 3 steps:
  1. Increment the sequence by a negative number which is the difference between the current value and the new value (900001 - 400000)
  2. Get the next value from dual
  3. Re-adjust the increment of the sequence back to 1.

In SQL this can be done as follows:

alter sequence my_sequence increment by -500001;
select my_sequence.nextval from dual;
alter sequence my_sequence increment by 1;
Post a Comment