Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql sort string number

Tags:

mysql

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

like image 263
sreenavc Avatar asked Mar 24 '11 09:03

sreenavc


People also ask

How do I sort numbers in a String?

Convert each element in the String array obtained in the previous step into an integer and store in into the integer array. The sort() method of the Arrays class accepts an array, sorts the contents of it in ascending order. Sort the integer array using this method.


2 Answers

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.

like image 22
MarzSocks Avatar answered Sep 20 '22 21:09

MarzSocks


Quickest, simplest? use * 1

select * from tbl order by number_as_char * 1 

The other reasons for using * 1 are that it can

  1. survive some horrendous mishaps with underflow (reduced decimal precision when choosing what to cast to)
  2. works (and ignores) columns of purely non-numeric data
  3. strips numeric portions of alphanumeric data, such as 123A, 124A, 125A
like image 194
RichardTheKiwi Avatar answered Sep 22 '22 21:09

RichardTheKiwi