The reasons why you should not reset the value if it is used:
What happens if you have 20 records and delete records 5-10? You have a gap in the middle that re-setting the sequence will not solve. Sequences will never generate a free sequence of spaces of numbers , perfect 1, 2 .. n.
If you call .nextval
and do not use the value that it is gone. Are you going to reset and recreate the sequence? If you run the insert and cancel it, and Oracle rollback , then what you did, these values ββdisappeared. If you install nocache
, then you will have fewer spaces, but with the price of getting into performance; Is it worth it?
The cache should indicate the number of attachments that you expect to make at any time for all sessions in order to avoid any performance issues. The sequences are designed to provide a very fast scalable way to create a surrogate key without locks, etc., so as not to generate a set of positive integers.
At the end of the day, this does not matter at all. If you rely on a continuous sequence as the key to your table, then you have a problem with your data, not the sequences.
Answering the question:
To answer your question you need:
Finding the maximum value means that you will need to recreate the sequence dynamically at the expense of another performance hit.
If you try to insert something into your table while this happens, it will fail and can invalidate any triggers or other objects that use the sequence:
declare l_max_value number; begin select max(id) into l_max_value from my_table; execute immediate 'drop sequence my_sequence_name';
As I said, this is not recommended, and you should just ignore any spaces.
Update - aka Best Answer Thanks Jeffrey Kemp :
Unlike the documentation recommendation, as Jeffrey Kemp suggested in the comments, the way to do this is without discarding or re-creating the sequence.
Namely: by:
- Develop the difference between the maximum
id
in your table and the current sequence value. - Sequence change to increase by this negative number
- Change the sequence to increase by 1 again.
The advantages of this are that the object still exists, and triggers, grants, etc. still supported. The disadvantage, as I see it, is that if another session increases by this negative number at the same time as yours, you may go back too far.
Here's a demo:
Set up the test:
SQL> create sequence test_seq 2 start with 1 3 increment by 1 4 nomaxvalue 5 nocycle 6 nocache; Sequence created. SQL> SQL> create table tmp_test ( id number(16) ); Table created. SQL> SQL> declare 2 l_nextval number; 3 begin 4 5 for i in 1 .. 20 loop 6 insert into tmp_test values ( test_seq.nextval ); 7 end loop; 8 9 end; 10 / PL/SQL procedure successfully completed. SQL> SQL> select test_seq.currval from dual; CURRVAL
Cancel sequence
SQL> SQL> declare 2 3 l_max_id number; 4 l_max_seq number; 5 6 begin 7 8