Generate an integer sequence in MySQL?

MySQLMySQLi Database

To create an integer sequence in MySQL, use AUTO_INCREMENT. Remember, there is no special command to create an integer sequence. The AUTO_INCREMENT will help to create an integer sequence in MySQL.

The AUTO_INCREMENT begins from 1 by default. You can change with another number with the help of alter command. Let us see an example. Suppose you have the initial value as 1000. With that, the next number will be 1000 + 1 = 1001.

Here is an example of AUTO_INCREMENT. The query to create a table −

mysql> create table AutoIncrementDemo
   −> (
      −> EmployeeId int AUTO_INCREMENT,
      −> primary key(EmployeeId)
   −> );
Query OK, 0 rows affected (0.54 sec)

Inserting records that generates an integer sequence. The query is as follows −

mysql> insert into AutoIncrementDemo values();
Query OK, 1 row affected (0.13 sec)

mysql> insert into AutoIncrementDemo values();
Query OK, 1 row affected (0.27 sec)

mysql> insert into AutoIncrementDemo values();
Query OK, 1 row affected (0.09 sec)

mysql> insert into AutoIncrementDemo values();
Query OK, 1 row affected (0.09 sec)

mysql> insert into AutoIncrementDemo values();
Query OK, 1 row affected (0.09 sec)

mysql> insert into AutoIncrementDemo values();
Query OK, 1 row affected (0.07 sec)

You can check the integer sequence with the help of select statement. The query is as follows −

mysql> select *from AutoIncrementDemo;

The following is the output −

+------------+
| EmployeeId |
+------------+
|          1 |
|          2 |
|          3 |
|          4 |
|          5 |
|          6 |
+------------+
6 rows in set (0.00 sec)
raja
Published on 10-Jan-2019 07:19:20
Advertisements