Question
How to use Oracle DB sequences without losing the next sequence number in case of roll-back?
Facts collected
1 - In Oracle, we can create a sequence and use two main calls (NEXTVAL
) to get the next sequence value and (CURRVAL
) to get the current sequence value.
2 - When we call (NEXTVAL
) will always get the next number and we will lose it if there is a rollback. In other words, Oracle sequence does not care if there is a roll-back or commit; whenever you are calling it, it will give a new number.
Possible answers I found so far
1 - I was thinking to create a simple table with one column of type (NUMBER) to service this purpose. Simply pick the value and use it. If operation succeeded I will increment column value. Otherwise, I will keep it as it is for the next application call.
2 - Another way I found here (How do I reset a sequence in Oracle?) is to use (ALTER SEQUENCE
) like the following if I want to go one step back.
That is, if the sequence is at 101, I can set it to 100 via
ALTER SEQUENCE serial INCREMENT BY -1;
SELECT serial.NEXTVAL FROM dual;
ALTER SEQUENCE serial INCREMENT BY 1;
Conclusion
Are any of the suggested solutions is good? Is their any better approach?