Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ORDER BY varchar field as number?

Tags:

I have problem with sort/order by, not working like I need.

SELECT `proc` FROM `table` ORDER BY `proc` DESC;

Result:

80.0 proc
70.0 proc
60.0 proc
50.0 proc
40.0 proc
200.0 proc
20.0 proc
190.0 proc
180.0 proc
170.0 proc
160.0 proc
150.0 proc
140.0 proc
130.0 proc
120.0 proc
110.0 proc
100.0 proc

What I need is:

200.0 proc
190.0 proc
180.0 proc
170.0 proc
160.0 proc
150.0 proc
140.0 proc
130.0 proc
120.0 proc
110.0 proc
100.0 proc
90.0 proc
80.0 proc
70.0 proc
60.0 proc
50.0 proc
40.0 proc
20.0 proc

How to do it ?

like image 803
jmp Avatar asked Jul 30 '12 19:07

jmp


People also ask

Can I use varchar for numbers?

As the name suggests, varchar means character data that is varying. Also known as Variable Character, it is an indeterminate length string data type. It can hold numbers, letters and special characters.

Can we use number in ORDER BY clause?

The rule checks for ORDER BY clauses that reference select list columns using the column number instead of the column name. The column numbers in the ORDER BY clause impairs the readability of the SQL statement.

How do you ORDER BY a column?

Select a cell in the column you want to sort. On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, under Column, in the Sort by or Then by box, select the column that you want to sort by a custom list.

What is ORDER BY 1 desc in SQL?

it simply means sorting the view or table by 1st column of the query's result.


1 Answers

It looks like "proc" is a string (varchar field), so it gets ordered lexically. If it is so, you can probably order it by

SELECT `proc` FROM `table` ORDER BY convert(`proc`, decimal) DESC;

Please note that such queries will be very slow, and for any serious usage it's better to use numeric columns for storing numeric data.

like image 121
che Avatar answered Sep 20 '22 16:09

che