I have a column of type varchar that stores many different numbers. Say for example there are 3 rows: 17.95, 199.95 and 139.95.How can i sort that field as numbers in mysql
-
5Why is it not a number in the first place?Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2011-03-24 09:58:32 +00:00Commented Mar 24, 2011 at 9:58
-
If you have lots of records and you want to convert in each query, it is going to be a nightmare. Please review your database design again, use an appropriate column type.Sarwar Erfan– Sarwar Erfan2011-03-24 10:03:56 +00:00Commented Mar 24, 2011 at 10:03
-
Wordpress stores custom fields as text. If you have a custom field such as a lat/lon, it's slow to convert to do lookups if your table is large. Storing as zero padded numbers in your text field is the only way to avoid the conversion and allow proper sort. Caution! Negative numbers stored as text sort the OPPOSITE direction as real numbers!Neal Bozeman– Neal Bozeman2020-04-01 23:25:12 +00:00Commented Apr 1, 2020 at 23:25
6 Answers
Quickest, simplest? use * 1
select *
from tbl
order by number_as_char * 1
The other reasons for using * 1 are that it can
- survive some horrendous mishaps with underflow (reduced decimal precision when choosing what to cast to)
- works (and ignores) columns of purely non-numeric data
- strips numeric portions of alphanumeric data, such as 123A, 124A, 125A
6 Comments
If you need to sort a char column containing text AND numbers then you can do this.
tbl contains: 2,10,a,c,d,b,4,3
select * from tbl order by number_as_char * 1 asc, number_as_char asc
expected output: 2,3,4,10,a,b,c,d
If you don't add the second order by argument only numbers will be sorted - text actually gets ignored.
1 Comment
Use a CAST or a CONVERT function.
7 Comments
This approach is helpful when sorting text as numbers:
SELECT `my_field`
FROM `my_table`
ORDER BY `my_field` + 0;
Found the solution on http://crodrigues.com/trick-mysql-order-string-as-number/.
Comments
Pad the string with leading zeroes:
ORDER BY LPAD(`column`,<max length of string>,"0")
2 Comments
If you really have to you can do this if your source data is compatible:
SELECT column FROM table ORDER BY CAST(column AS DECIMAL(10,2))
It's not going to be very fast for large data sets though. If you can you should change the schema to use DECIMAL in the first place though. Then it can be properly indexed for better performance.
5 Comments
DECIMAL. I'll update my answer with exactly the output I got. Give it a try, am I overlooking something? I otherwise don't get the right order unless that ORDER BY CAST is specified.SELECT bar, CAST(bar AS DECIMAL) FROM foo As it is your test numbers are all significantly different* 1