How to increment all the rows of a particular column by 1 in a single MySQL query (ID column +1)?

MySQLMySQLi Database

To increment all the rows of a particular ID column by 1, you need to use UPDATE command and update the table. The syntax of the query is as follows. We have also used ORDER BY here

UPDATE yourTableName SET yourIdColumnName=yourIdColumnName+1 ORDER BY yourIdColumnName DESC;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table IdColumnadd1Demo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
   - > );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.12 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.18 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.17 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.08 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.13 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.25 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.40 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from IdColumnadd1Demo;

The following is the output

+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
+----+
8 rows in set (0.00 sec)

Here is the query to adjust the MySQL ID column+1

mysql> update IdColumnadd1Demo set Id=Id+1 Order By Id DESC;
Query OK, 8 rows affected (0.18 sec)
Rows matched: 8 Changed: 8 Warnings: 0

Check the table records once again.

The query is as follows

mysql> select *from IdColumnadd1Demo;

The following is the output

+----+
| Id |
+----+
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
+----+
8 rows in set (0.00 sec)
raja
Published on 19-Mar-2019 11:39:33
Advertisements