SQL SEQUENCES (original) (raw)

Last Updated : 13 Jun, 2026

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.

SQL Sequences Working

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;

**Example 1: Creating a Sequence in Ascending Order

CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;

**Example 2: Creating a Sequence in Descending Order

CREATE SEQUENCE sequence_2
start with 100
increment by -1
min value 1
max value 100
cycle;

Using SQL Sequences in Database Operations

A sequence can be used across multiple tables to generate unique values automatically, ensuring consistency and uniqueness.

Example: Using a Sequence to Insert Values

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-122653

Cache Management in SQL Sequences

CACHE 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_3
START WITH 1
INCREMENT BY 1
CACHE 10;

Features of SQL Sequences

The functionality of SQL sequences is defined by the following features: