There is another way to reset a sequence in Oracle: set the maxvalue
and cycle
properties. When the nextval
of the sequence hits the maxvalue
, if the cycle
property is set then it will begin again from the minvalue
of the sequence.
The advantage of this method compared to setting a negative increment by
is the sequence can continue to be used while the reset process runs, reducing the chance you need to take some form of outage to do the reset.
The value for maxvalue
has to be greater than the current nextval
, so the procedure below includes an optional parameter allowing a buffer in case the sequence is accessed again between selecting the nextval
in the procedure and setting the cycle
property.
create sequence s start with 1 increment by 1;
select s.nextval from dual
connect by level <= 20;
NEXTVAL
----------
1
...
20
create or replace procedure reset_sequence ( i_buffer in pls_integer default 0)
as
maxval pls_integer;
begin
maxval := s.nextval + greatest(i_buffer, 0); --ensure we don't go backwards!
execute immediate 'alter sequence s cycle minvalue 0 maxvalue ' || maxval;
maxval := s.nextval;
execute immediate 'alter sequence s nocycle maxvalue 99999999999999';
end;
/
show errors
exec reset_sequence;
select s.nextval from dual;
NEXTVAL
----------
1
The procedure as stands still allows the possibility that another session will fetch the value 0, which may or may not be an issue for you. If it is, you could always:
minvalue 1
in the first alternextval
fetch nocycle
property into another procedure, to be run at a later date (assuming you want to do this).