Categories: DBMS

SQL: Sequence

What is an SQL Sequence?

Database systems offer sequence to produce unique numeric values in a series according to defined standards.

  • In SQL, a sequence is a user-defined schema-bound entity that generates a set or sequence of numbers with important ordering.
  • Some database applications may demand that each table row include unique values. In many circumstances, sequences are useful for quickly generating values.
Using AUTO_INCREMENT column

The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and leave the rest to MySQL to take care of.

Creating a Sequence

Syntax :

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

where,

  • sequence_name: Name of the sequence.
  • initial_value: starting value from where the sequence starts. Initial_value should be greater than or equal to minimum value and less than equal to maximum value.
  • increment_value: Value by which sequence will increment itself. Increment_value can be positive or negative.
  • minimum_value: Minimum value of the sequence.
  • maximum_value: Maximum value of the sequence.
  • cycle: When sequence reaches its set_limit it starts from the beginning.
  • nocycle: An exception will be thrown if the sequence exceeds its max_value.
Example
CREATE SEQUENCE seq_1
start with 0
increment by 1
minvalue 0
maxvalue 99
cycle;

Now let’s insert a value to a Student table using the above-created sequence:

IDNAME
1Rabecca
2 Varun
Student

Query to insert a record into the Student table:

INSERT INTO Student VALUE(seq_1.nextval, 'John');

Output:

IDNAME
1Rabecca
2 Varun
3John
Student

Note: If we use nextval, the sequence will continue to grow even if no records are added to the table.

Note: also read about SQL: SET Operations

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima
Tags: SQL Sequence

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago