How To Use Sequence (autonumber) in Oracle
Description
A sequence is an object, which is used to generate a sequence number(autonumber) in Oracle.
Sequence
A sequence is an object, which is used to generate a sequence of numbers in Oracle. You can use sequence to automatically generate the primary key values.
Sequence of numbers are generated independently of tables, so the same sequence is used for one or more multiple tables.
When a sequence is created, you can access the values in SQL statement.
Syntax
- Create sequence sequence_name
- Minvalue value
- Maxvalue value
- Start with value
- Increment by value
- Cache value;
Sequences are created by the use of the create sequence statement.
Minimum value
Specify the minimum value of the sequences.
Maximum value
Specify the maximum value the sequence, which can be generated.
Start with value
Specify the first sequence number, which you want to be generate.
Increment By
How to increment the sequence. The integer value can be any positive or negative value but it cannot be zero.
If it has the positive value, the value is in an ascending order. If the value is negative, the value is in descending order.
Cache
Cache is used for the speed access but cache memory is deleted, when the database is shutdown.
Cache default value is 20.
Example
- CREATE SEQUENCE Employee_seq
- MINVALUE 1
- MAXVALUE 999999999999999999999999999
- START WITH 7008
- INCREMENT BY 1
- CACHE 20;
Inserting values
- INSERT INTO Employee
- (Emp_id, Emp_name, Emp_job)
- VALUES
- (Employee_seq.NEXTVAL, 'Blick', 'marketing');
- INSERT INTO Employee
- (Emp_id, Emp_name, Emp_job)
- VALUES
- (Employee_seq.NEXTVAL, 'Andrew', 'HR');
- INSERT INTO Employee
- (Emp_id, Emp_name, Emp_job)
- VALUES
- (Employee_seq.NEXTVAL, 'Bhusan', 'Clerk');
- INSERT INTO Employee
- (Emp_id, Emp_name, Emp_job)
- VALUES
- (Employee_seq.NEXTVAL, 'Wynk', 'Sales');
Drop Sequence
First, you have to create a sequence in Oracle and you need to drop a sequence in your database.
Syntax
- Drop Sequence Sequence_name;
Sequence name is a name, which you want to drop sequence in your database.
Example
- Drop sequence Employee_seq;
Summary
Thus, we learnt, a sequence is an object, which is used to generate a sequence number (autonumber) in Oracle. We learnt, how to use sequence in Oracle with the examples.