MySQL update a column with an int based on order?

MySQLMySQLi Database

The syntax is as follows to update a column with an int based on order

set @yourVariableName=0;
update yourTableName
set yourColumnName=(@yourVariableName:=@yourVariableName+1)
order by yourColumnName ASC;

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

mysql> create table updateColumnDemo
   -> (
   -> Id int,
   -> OrderCountryName varchar(100),
   -> OrderAmount int
   -> );
Query OK, 0 rows affected (1.76 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into updateColumnDemo(Id,OrderCountryName) values(10,'US');
Query OK, 1 row affected (0.46 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(20,'UK');
Query OK, 1 row affected (0.98 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(30,'AUS');
Query OK, 1 row affected (0.77 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(40,'France');
Query OK, 1 row affected (1.58 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from updateColumnDemo;

The following is the output

+------+------------------+-------------+
| Id   | OrderCountryName | OrderAmount |
+------+------------------+-------------+
| 10   | US               | NULL        |
| 20   | UK               | NULL        |
| 30   | AUS              | NULL        |
| 40   | France           | NULL        |
+------+------------------+-------------+
4 rows in set (1.00 sec)

Here is the query to update a column with an int based on order

mysql> set @sequenceNumber=0;
Query OK, 0 rows affected (0.00 sec)
mysql> update updateColumnDemo
   -> set OrderAmount=(@sequenceNumber:=@sequenceNumber+1)
   -> order by OrderAmount ASC;
Query OK, 4 rows affected (0.25 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check the table records once again.

The query is as follows

mysql> select *from updateColumnDemo;

The following is the output

+------+------------------+-------------+
| Id   | OrderCountryName | OrderAmount |
+------+------------------+-------------+
| 10   | US               | 1           |
| 20   | UK               | 2           |
| 30   | AUS              | 3           |
| 40   | France           | 4           |
+------+------------------+-------------+
4 rows in set (0.00 sec)
raja
Published on 29-Mar-2019 11:39:11
Advertisements