Monday, June 8, 2020

Database - Create a sequence

  • Sequence is a feature supported by some database systems to produce unique values on demand. Some DBMS like MySQL supports AUTO_INCREMENT in place of Sequence.
  • AUTO_INCREMENT is applied on columns, it automatically increments the column value by 1 each time a new record is inserted into the table.
Creating a Sequence


Syntax:
CREATE SEQUENCE sequence-name
    START WITH initial-value
    INCREMENT BY increment-value
    MAXVALUE maximum-value
    CYCLE | NOCYCLE;

Initial-value specifies the starting value for the Sequence.
Increment-value is the value by which sequence will be incremented.
Maximum-value specifies the upper limit or the maximum value upto which sequence will increment itself.
CYCLE specifies that if the maximum value exceeds the set limit, sequence will restart its cycle from the begining.
NO CYCLE specifies that if sequence exceeds MAXVALUE value, an error will be thrown.

Using Sequence:
Creating a sequence, which will start from 1, increment by 1 with a maximum value of 999.

Example 1:
CREATE SEQUENCE seq_1
START WITH 1
INCREMENT BY 1
MAXVALUE 999
CYCLE;

INSERT INTO class VALUE(seq_1.nextval, 'anu');

Example 2:
CREATE SEQUENCE "USER_EVENT_SEQ"  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE ;

select USER_EVENT_SEQ.nextVal from dual

For more details click here.Oracle Docs


No comments:

Post a Comment

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...