![]() |
VOOZH | about |
SQL sequences are used to generate unique numbers automatically for things like primary keys and IDs. They help keep data organized and consistent in a database.
When creating a sequence, we set the start value, increment and limits. It can also restart (cycle) when it reaches the maximum.
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE min_value
MAXVALUE max_value
CYCLE | NOCYCLE;
CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;
sequence_1.CREATE SEQUENCE sequence_2
start with 100
increment by -1
min value 1
max value 100
cycle;
sequence_2.A sequence can be used across multiple tables to generate unique values automatically, ensuring consistency and uniqueness.
Create a students table and use a sequence to automatically generate unique student IDs using the NEXTVAL function.
Query:
CREATE TABLE students
(
ID number(10),
NAME char(20)
);
INSERT into students VALUES
(sequence_1.nextval,'Shubham');
INSERT into students VALUES
(sequence_1.nextval,'Aman');
Output
👁 Screenshot-2026-01-29-122653CACHE stores sequence values in memory to improve performance and reduce disk access.
Example: With CACHE 15, sequence values are preallocated in memory. Unused values may be skipped after a restart. Use NOCACHE to avoid gaps, but it is slower.
Creating a Sequence with Cache
CREATE SEQUENCE sequence_3START WITH 1INCREMENT BY 1CACHE 10;
The functionality of SQL sequences is defined by the following features: