MySQL select order by acts like a string (not a number)?


You can use the following syntax if your column has varchar data type −

select yourColumnName FROM yourTableName ORDER BY yourColumnName +0 DESC;

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

mysql> create table selectOrderdemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> RankNumber varchar(100)
   -> );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into selectOrderdemo(Name,RankNumber) values('Larry',-100);
Query OK, 1 row affected (0.23 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('John',50);
Query OK, 1 row affected (0.13 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('Bob',0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('Carol',-110);
Query OK, 1 row affected (0.23 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('David',98);
Query OK, 1 row affected (0.21 sec

Display all records from the table using select statement. The query is as follows −

mysql> select *from selectOrderdemo;

Here is the output −

+----+-------+------------+
| Id | Name  | RankNumber |
+----+-------+------------+
| 1  | Larry | -100       |
| 2  | John  | 50         |
| 3  | Bob   | 0          |
| 4  | Carol | -110       |
| 5  | David | 98         |
+----+-------+------------+
5 rows in set (0.00 sec)

Here is the query to select order by that acts like number.

Case 1 − If you want the result in descending order, The query is as follows −

mysql> select RankNumber FROM selectOrderdemo ORDER BY RankNumber+0 DESC;

Here is the output −

+------------+
| RankNumber |
+------------+
| 98         |
| 50         |
| 0          |
| -100       |
| -110       |
+------------+
5 rows in set (0.00 sec)

Case 2 − If you want the result in ascending order, The query is as follows −

mysql> select RankNumber FROM selectOrderdemo ORDER BY RankNumber+0;

Here is the output −

+------------+
| RankNumber |
+------------+
| -110       |
| -100       |
| 0          |
| 50         |
| 98         |
+------------+
5 rows in set (0.00 sec)

Case 3 − If you want all the columns, use the below query −

mysql> select * FROM selectOrderdemo ORDER BY RankNumber+0 DESC;

Here is the output −

+----+-------+------------+
| Id | Name  | RankNumber |
+----+-------+------------+
| 5  | David | 98         |
| 2  | John  | 50         |
| 3  | Bob   | 0          |
| 1  | Larry | -100       |
| 4  | Carol | -110       |
+----+-------+------------+
5 rows in set (0.00 sec)

Updated on: 30-Jul-2019

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements