Sequences (Identity)

Most of the tables consist of an ID or identity column to identify the rows into the table. Microsoft SQL has an defined property IDENTITY column that increment the value automatically when the data is inserted into the table.
But Oracle don't have any similar property defined but not to worry this can be achived by the help of SEQUENCES.

Lets consider the table  Employee (
ID,
Name,
Department)

Now this table cointains ID and if want to always insert the next value after the maximum value present in table we can achieve this with the help of sequences.

Syntax:
CREATE SEQUENCE <sequence_name>
    MINVALUE <value>
    MAXVALUE <value>
    START WITH <value>
    INCREMENT BY <value>
    CACHE <value> ;

Here:
<sequence_name> : is name for the sequence
MINVALUE : is the minimum value for the column
MAXVALUE: is the maximum value for the column by default it will be 999999999999999999999999999
START WITH: is the starting value
INCREMENT BY: is the value by the which the current value will be inceremented to get the next value
CACHE : is number of records that should stay in cache for perfomance

For ex:
CREATE SEQUENCE Employee_seq_id
    MINVALUE 1
    MAXVALUE 99999999
    START WITH 1
    INCREMENT BY 1
    CACHE 100 ;

INSERT INTO EMPLOYEE
VALUES(Employee_seq_id.nextval, 'John','Sales')

Here:
nextval will return the next value that should be inserted into the ID column

No comments:

Post a Comment