tags:

views:

193

answers:

3

Hi,

I have a table say tblSwap with a column StroreVals.

StroreVals


20

21

29

11

10

5

7

I want to get the result in descending order using SQL SERVER 2005.

How to do?

If you fire SELECT StroreVals FROM tblSwap ORDER BY StroreVals DESC

The output is 7

5

29

21

20

11

10

Also, if it is like "Abc", "Def","Azy","kly"? Please help

+5  A: 

You have stored the numbers in a varchar field, but you want them to be ordered like numbers.

Do this, convert the field to a numeric one for the sort:

SELECT StroreVals  
FROM tblSwap ORDER BY convert(int,StroreVals) DESC

Assumptions: all the values can be converted to int, otherwise, you'll get an error.

tekBlues
+1 - Provided assumption is correct
kristof
+3  A: 

if casting isn't an option you can do this:

SELECT StroreVals 
FROM tblSwap 
order by right(replicate('0', 11) + StroreVals, 10)
Mladen Prajdic
+1. Interesting approach
kristof
Yes, very intelligent idea, a good way to solve this if you are afraid that non numeric values can be present.
tekBlues
Is using replicate faster than right('00000000000' + StroreVals, 10)?
RedFilter
Brilliant answer man. I liked your way of solving problem
priyanka.sarkar
@OrbMan: i'd say it's slower. i just wrote it this way because i'm used to it :) but the speed difference can be observed if you have millions of rows.... maybe. i haven't tested it though.
Mladen Prajdic
A: 

If you store your data as varchar it is by default sorted as varchar with the sorting order specified by the collation settings

when you have string: '3','111','2' and you sort desc you will get '3','2','111' in the same way as if you had strings 'c','aaa','b' sort desc as 'c','b','aaa'

If your field stores numbers only then store them as numbers or use the casting as suggested by tekBlues

If you have both numbers and strings and are not happy with the default sorting behaviour for strings you may need to define your own sorting criteria e.g. solution suggested by Mladen

kristof