What is the purpose of ORDER BY columnname*1 in MySQL?


MySQL will implicitly convert the column into a number. Following is the syntax −

select * from yourTableName
 order by yourColumnName*1;

Let us first create a −

mysql> create table DemoTable1441
   -> (
   -> Id varchar(30)
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1441 values('301');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1441 values('23');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1441 values('345');
Query OK, 1 row affected (0.42 sec)
mysql> insert into DemoTable1441 values('10');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1441 values('38');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select −

mysql> select * from DemoTable1441;

This will produce the following output −

+------+
| Id   |
+------+
| 301  |
| 23   |
| 345  |
| 10   |
| 38   |
+------+
5 rows in set (0.00 sec)

Following is the query to use order by columnname*1 −

mysql> select * from DemoTable1441
   ->  order by id*1;

This will produce the following output −

+------+
| Id   |
+------+
| 10   |
| 23   |
| 38   |
| 301  |
| 345  |
+------+
5 rows in set (0.00 sec)
raja
Published on 12-Nov-2019 06:56:55
Advertisements