Sort in MySQL and increment value?


You can use update command along with a user-defined variable. Let us first create a table −

mysql> create table DemoTable
(
   FirstName varchar(20),
   Position int
);
Query OK, 0 rows affected (0.71 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',100);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Robert',120);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('David',130);
Query OK, 1 row affected (0.16 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+----------+
| FirstName | Position |
+-----------+----------+
| Chris    | 100       |
| Robert   | 120       |
| David    | 130       |
+-----------+----------+
3 rows in set (0.00 sec)

Following is the query to sort field and increment value by 10 −

mysql> SET @myPosition := 100;
Query OK, 0 rows affected (0.00 sec)
mysql> update DemoTable set Position = @myPosition:=@myPosition+10 ORDER BY
Position;
Query OK, 1 row affected (0.17 sec)
Rows matched: 3 Changed: 1 Warnings: 0

Let us check the records once again from the table: mysql> select *from DemoTable -

This will produce the following output −

+-----------+----------+
| FirstName | Position |
+-----------+----------+
| Chris     | 110      |
| Robert    | 120      |
| David     | 130      |
+-----------+----------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements