SQL Sequence
SQL Sequence
SEQUENCE
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database
systems to produce unique values on demand.
A sequence is a user defined schema bound object that generates a sequence of numeric
values.
Sequences are frequently used in many databases because many applications require
each row in a table to contain a unique value and sequences provides an easy way to
generate them.
The sequence of numeric values is generated in an ascending or descending order at
defined intervals and can be configured to restart when exceeds max_value.
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
cycle: When sequence reaches its set limit it starts from beginning.
1
SEQUENCE
Example 1:
Above query will create a sequence named sequence_1.Sequence will start from 1 and
will be incremented by 1 having maximum value 100. Sequence will repeat itself from
start value after exceeding 100.
To get the next value of the sequence, you use the NEXTVAL
2
SEQUENCE
To get the current value of the sequence, you use the CURRVAL
3
SEQUENCE
Example 2:
Following is the sequence query creating sequence in descending order.
CREATE SEQUENCE sequence_2
start with 100
increment by -1
minvalue 1
maxvalue 100
cycle;
4
SEQUENCE
Above query will create a sequence named sequence_2.Sequence will start from 100 and
should be less than or equal to maximum value and will be incremented by -1 having
minimum value 1.
Example to use sequence : create a table named students with columns as id and name.
CREATE TABLE students
(
ID number(3),
NAME char(10)
);
5
SEQUENCE
DROP SEQUENCE:
Remove a Sequence.
Syntax:
DROP SEQUENCE sequence_name;
Example:
DROP SEQUENCE sequence_2;
6
SEQUENCE
Synonyms
SQL Synonyms is an alias for a table or a Schema object in a database. They are used to
protect client applications from the changes made to name or location of an object.
Public Synonyms
Public Synonyms are owned by PUBLIC schema in a database. Public synonyms can be
referenced by all users in the database. They are created by the application owner for
the tables and other objects such as procedures and packages so the users of the
application can see the objects. To create a PUBLIC Synonym, you have to use keyword
PUBLIC .
Example:
7
SEQUENCE
Private Synonyms
Private Synonyms are used in a database schema to hide the true name of a table,
procedure, view or any other database object.
Private synonyms can be referenced only by the schema that owns the table or object.
Example:
Drop a Synonym
Synonyms can be dropped using DROP Synonym command. If you are dropping a public
Synonym, you have to use the keyword public in the drop statement.
8
SEQUENCE
Example: