views:

328

answers:

2

Can you please help me in solving this problem. I am trying to order the results of an SQL query by date, but I'm not getting the results I need.

The query I'm using is:

SELECT date FROM tbemp ORDER BY date ASC

Results are:

01/02/2009
03/01/2009
04/06/2009
05/03/2009
06/12/2008
07/02/2009

Results should be:

06/12/2008
03/01/2009
01/02/2009
07/02/2009

I need to select the date in the format above.

Your help is much appreciated.

+5  A: 

It sounds to me like your column isn't a date column but a text column (varchar/nvarchar etc). You should store it in the database as a date, not a string.

If you have to store it as a string for some reason, store it in a sortable format e.g. yyyy/MM/dd.

As najmeddine shows, you could convert the column on every access, but I would try very hard not to do that. It will make the database do a lot more work - it won't be able to keep appropriate indexes etc. Whenever possible, store the data in a type appropriate to the data itself.

Jon Skeet
or yyyy-mm-dd even better
dusoft
@dusoft: It doesn't really matter what separator you use, so long as it's in the right order of significance.
Jon Skeet
@Jon: It's easier to compare two hyphens than two slashes, because you don't have to deal with the angle. :-D
Zed
+5  A: 

It seems that your date column is not of type datetime but varchar. You have to convert it to datetime when sorting:

select date
from tbemp
order by convert(datetime, date, 103) ASC

style 103 = dd/MM/yyyy (msdn)

najmeddine
This won't sort correctly if the current language and date format settings cause interpret aa/bb/cccc as month/day/year, as is the case for most US installations of SQL Server. (I'm assuming from the use of CONVERT that this is T-SQL, so you can specify style 103 as the optional third parameter to CONVERT and override any language or dateformat context.)
Steve Kass
thanks for the info.
najmeddine