Ordering a varchar column in MySQL in an Excel-like manner
-
30-09-2019 - |
Question
I have a varchar column with mixed data- strings, integers, decimals, blank strings, and null values. I'd like to sort the column the same way that Excel would, first sorting numbers and then sorting the strings. For example:
- 1
- 2
- 3
- 3.5
- 10
- 11
- 12
- alan
- bob
- carl
- (blank/null)
- (blank/null)
I've tried doing something like 'ORDER BY my_column+0' which sorts the numbers correctly but not the strings. I was hoping someone might know of an efficient way to accomplish this.
MartinofD's suggestion works for the most part and if I expand on it a little bit I can get exactly what I want:
SELECT a FROM test ORDER BY a IS NULL OR a='', a<>'0' AND a=0, a+0, a;
Pretty ugly though and I'm not sure if there are any better options.
Solution 2
This works:
SELECT a FROM test ORDER BY a IS NULL OR a='', a<>'0' AND a=0, a+0, a;
Any more efficient/elegant solution would be welcome however.
OTHER TIPS
That's because my_column+0
is equal for all strings (0).
Just use ORDER BY my_column+0, my_column
mysql> SELECT a FROM test ORDER BY a+0, a;
+-------+
| a |
+-------+
| NULL |
| alan |
| bob |
| carl |
| david |
| 1 |
| 2 |
| 3 |
| 3.5 |
| 10 |
| 11 |
| 12 |
+-------+
12 rows in set (0.00 sec)
If you strictly need the numbers to be above the strings, here's a solution (though I'm not sure how quick this will be on big tables):
mysql> SELECT a FROM test ORDER BY (a = CONCAT('', 0+a)) DESC, a+0, a;
+-------+
| a |
+-------+
| 1 |
| 2 |
| 3 |
| 3.5 |
| 10 |
| 11 |
| 12 |
| alan |
| bob |
| carl |
| david |
| NULL |
+-------+
12 rows in set (0.00 sec)