Ordering string as a number in a database?


To order string as a number, use CAST(). Following is the syntax −

select *from yourTableName ORDER BY CAST(yourColumnName AS SIGNED) DESC;

Let us first create a table −

mysql> create table DemoTable
   (
   Id varchar(100)
   );
Query OK, 0 rows affected (0.18 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('3');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values('20');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values('34');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values('21');
Query OK, 1 row affected (0.06 sec)

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

mysql> insert into DemoTable values('90');
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+
| Id   |
+------+
| 3    |
| 20   |
| 34   |
| 21   |
| 78   |
| 90   |
+------+
6 rows in set (0.00 sec)

Following is the query to ordering integer numbers −

mysql> select *from DemoTable ORDER BY CAST(Id AS SIGNED) DESC;

This will produce the following output −

+------+
| Id   |
+------+
| 90   |
| 78   |
| 34   |
| 21   |
| 20   |
| 3    |
+------+
6 rows in set (0.02 sec)

Updated on: 30-Jul-2019

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements