René Nyffenegger's collection of things on the web | |
René Nyffenegger on Oracle - Most wanted - Feedback
- Follow @renenyffenegger
|
Sequences [Oracle] | ||
A sequence is a highly scalable, non-blocking, generator that generates unique numbers.
nextval
If nextval is invoked on a sequence, it makes sure that a unique number is generated
I create a sequence (named sequence_test)
create sequence sequence_test;
Then I use the sequence to generate a number. The sequence (or Oracle, for that matter) ensures that no other session or other call to
nextval within the same session gets the
same number from the sequence:
NEXTVAL ---------- 1
I then use
nextval again to generate another number:
NEXTVAL ---------- 2 currval
currval can only be used if a session has already called
nextval on a trigger. currval will then return the same number that was generated with nextval :
NEXTVAL ---------- 3 CURRVAL ---------- 3 CURRVAL ---------- 3 NEXTVAL ---------- 4 SQL> select sequence_test.currval from dual; CURRVAL ---------- 4 Demonstration
This is demonstrated in the following example. First, two tables are created:
create table seq_ex_a ( n number ); create table seq_ex_b ( s number, n number );
One table is populated with five rows:
insert into seq_ex_a values (55); insert into seq_ex_a values ( 3); insert into seq_ex_a values (27); insert into seq_ex_a values (81); insert into seq_ex_a values (32);
A sequence is generated:
create sequence seq_a start with 1 increment by 1;
Then, the values of table seq_ex_a are filled into seq_ex_b. The sequence generates a (as mentioned: unique) number by calling
nextval on it:
insert into seq_ex_b select seq_a.nextval, n from seq_ex_a;
The table's content:
select * from seq_ex_b;
This returns:
S N ---------- ---------- 1 55 2 3 3 27 4 81 5 32 nextval and currval in PL/SQLdeclare n number; begin select sequence_test.nextval into n from dual; dbms_output.put_line(n); end /
Apparently, in Oracle 11g, one is not required anymore to select from dual:
declare n number; begin n := sequence_test.nextval; dbms_output.put_line(n); end / Links
Sequences, together with triggers can be used to emulate
autonumbers.
|