Syntax error MySQL query to display ASC order in number column?

MySQL query to display ASC order in number column?



You can achieve this with the help of CAST() function. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score int
   );
Query OK, 0 rows affected (0.72 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Score) values(10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable(Score) values(100);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Score) values(11);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Score) values(97);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Score) values(78);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Score) values(89);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Score |
+----+-------+
| 1  | 10    |
| 2  | 100   |
| 3  | 11    |
| 4  | 97    |
| 5  | 78    |
| 6  | 89    |
+----+-------+
6 rows in set (0.00 sec)

Following is the query to set ASC order in number column −

mysql> select *from DemoTable order by cast(Score AS SIGNED INTEGER) ASC;

This will produce the following output −

+----+-------+
| Id | Score |
+----+-------+
| 1  | 10    |
| 3  | 11    |
| 5  | 78    |
| 6  | 89    |
| 4  | 97    |
| 2  | 100   |
+----+-------+
6 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements