Fakhar uz zaman February 2016

Order By Datetime in SQL Server not ordering Properly

I am trying to Order my dataset By Datetime in SQL Server. Using dd/mm/yyyy format. You can assume following query for simplicity.

Select CONVERT(NVARCHAR(50), DateColumn, 103) from myTable order by DateColumn DESC;

But it returns records only sorted by dd and ignores mm,yy.You can have a look over following data.

29/07/2015
26/09/2015
25/09/2015
25/09/2015
24/07/2015
22/09/2015
12/06/2015
01/10/2015

What should i do so that it may also include mm and yy as well while ordering.

Answers


Gordon Linoff February 2016

My guess is that your actual query is:

Select CONVERT(NVARCHAR(50), DateColumn, 103) as DateColumn
-------------------------------------------------^ Note alias here is the same as used in the order by
from myTable
order by DateColumn DESC;

The order by then uses the column definition in the select. You can change the name. Alternatively, use a qualified column name in the order by:

Select CONVERT(NVARCHAR(50), t.DateColumn, 103) as DateColumn
from myTable t
order by t.DateColumn DESC;

Post Status

Asked in February 2016
Viewed 3,154 times
Voted 10
Answered 1 times

Search




Leave an answer