How do I create and use a sequence in MySQL?

MySQLMySQLi Database

To create a sequence in MySQL, auto_increment can be used on the column. It starts from the value 1 and increments by 1 for each record when it is inserted.

First, a table is created with the help of CREATE table. The query for that is as follows −

mysql> CREATE table SequenceDemo
-> (
-> SequenceId int auto_increment,
-> primary key(SequenceId)
-> );
Query OK, 0 rows affected (1.22 sec)

After creating the table, the records can be inserted with the help of the insert command which is given as follows −

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.19 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.14 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.10 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.12 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.09 sec)

After inserting the records, they can be displayed with the help of the select statement which is given as follows −

mysql> SELECT * from SequenceDemo;

The following is the output obtained −

+------------+
| SequenceId |
+------------+
| 1          |
| 2          |
| 3          |
| 4          |
| 5          |
+------------+
5 rows in set (0.00 sec)

The sequence can be set with the help of the alter command.The syntax for this is given as follows −

alter table yourTableName auto_increment=Somevalue;

Now, the above syntax is used in the following query to set the sequence value as follows −

mysql> alter table SequenceDemo auto_increment = 500;
Query OK, 0 rows affected (0.17 sec)
Records: 0 Duplicates: 0 Warnings: 0

After that, the records are inserted from the value 500 in the table. This is given below −

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.15 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.15 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.05 sec)

All the records can be displayed with the select statement as follows −

mysql> SELECT * from SequenceDemo;

The output is given below

+------------+
| SequenceId |
+------------+
| 1          |
| 2          |
| 3          |
| 4          |
| 5          |
| 500        |
| 501        |
| 502        |
+------------+
8 rows in set (0.00 sec)

As can be seen from the above output, after 5 records the sequence id starts from 500 and is incremented by 1.

raja
Published on 22-Oct-2018 12:25:30
Advertisements