
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert Sequential Number in MySQL
You can insert sequential number in MySQL using session variable. The syntax is as follows −
SELECT @anyVariableName − = anyIntegerValue; UPDATE yourTableName SET yourColumnName = @anyVariableName − = @anyVariableName+IncrementStep;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table SequentialNumberDemo -> ( -> SequentialNumber int not null -> ); Query OK, 0 rows affected (0.84 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into SequentialNumberDemo values(100); Query OK, 1 row affected (0.11 sec) mysql> insert into SequentialNumberDemo values(10); Query OK, 1 row affected (0.22 sec) mysql> insert into SequentialNumberDemo values(9); Query OK, 1 row affected (0.15 sec) mysql> insert into SequentialNumberDemo values(60); Query OK, 1 row affected (0.11 sec) mysql> insert into SequentialNumberDemo values(50); Query OK, 1 row affected (0.14 sec) mysql> insert into SequentialNumberDemo values(40); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from SequentialNumberDemo;
The following is the output −
+------------------+ | SequentialNumber | +------------------+ | 100 | | 10 | | 9 | | 60 | | 50 | | 40 | +------------------+ 6 rows in set (0.00 sec)
Look at the above output, the number is not in a sequential order. Here is the query to get the sequential number beginning from 1. At first, set the sequence −
mysql> select @sequence: = 0;
The output −
+---------------+ | @sequence:= 0 | +---------------+ | 0 | +---------------+ 1 row in set (0.03 sec)
Now, the query to update and begin the sequence from 1 −
mysql> update SequentialNumberDemo set SequentialNumber = @sequence − = @sequence+1; Query OK, 6 rows affected (0.15 sec) Rows matched − 6 Changed − 6 Warnings − 0
Check the table records once again. The query is as follows −
mysql> select *from SequentialNumberDemo;
The following is the output −
+------------------+ | SequentialNumber | +------------------+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | +------------------+ 6 rows in set (0.00 sec)
Advertisements