views:

76

answers:

1

The query I am running is

select accountid from general order by accountid ASC

The result I get is

accountid
------------
1 
1001 
1002
10021 
10026
1006 
1007

Why is it not ordering correctly? It's a simple query and I am completely lost at how I can resolve this matter.

+11  A: 

The column type must be a numeric (int, number, bigint, etc) type..

Looks like right now it is a VARCHAR type column... which is sorted like a dictionary...

Garis Suero
if you cannot change the column type, you can order by to_number(account_id) (which is maybe quite slow)
Thilo
yes its varchar but why is it behaving like this can't we sort column with type varchar
farkhunda
@farkhunda. If you sort varchar, it sorts as strings (not numbers), and the output you show is the result
Thilo
@farkhunda: when ordering character strings, the values are not treated as integers - they are treated as character strings and ordered as character strings (just as shown). This was a reason why leading zeroes were popular in the dark ages of computing - alphabetic sorts sorted numbers with leading zeroes in the correct numeric order too.
Jonathan Leffler
@farkhunda: Strings sort character by character. The character `'2'` comes before `'6'`. So `'1002<whatever else the string contains, numbers letters what not'` is going to always come before `'1006'` If you want numeric sorting you will have to convert the strings to numbers before the sort. (Unless some of the strings aren't numbers, that would blow up then.)
Shannon Severance
Thanks everyone problem solved. I changed the query toselect accountid from general order by CONVERT(INT,accountid) ASC
farkhunda
If it is a new App or a new DB design, the best you can do is change the column type, CONVERT in a large amount of data could slowdown your query.
Garis Suero