Sort varchar date in ms sql server

In this programming tutorial we will learn how to sort the varchar date in ms sql server. I face the sorting problem of varchar date couple of days ago and then I decided to write a tutorial in it. I have a column registered_date of datetime datatype in users table; in that column the values are stored definitely in this format 2011-07-21 00:00:00.000. I wanted to get the distinct date in mm/dd/yyyy format and also wanted to sort the date(the purpose of this tutorial) according to my need.

I have easily converted the registered_date column of datetime into varchar and display date in mm/dd/yyyy format by using convert(varchar(10),registered_date,101) function but I failed to sort the date, also I failed to get the distinct date, like illustrated in following picture.
sort varchar date in ms sql server


So for fixation of this problem, I have written following query

Learn How to sort varchar date in ms sql server
Select Distinct convert(datetime,convert(varchar(10),registered_date,101)),   
convert(varchar, registered_date,101) As registered_date
FROM users Where Deleted ='false' order by convert(datetime,convert(varchar(10), registered_date,101)) desc

Output will be:-
2011-07-21 00:00:00.000      07/21/2011
2011-07-19 00:00:00.000      07/19/2011
2011-07-18 00:00:00.000      07/18/2011
2011-07-16 00:00:00.000      07/16/2011
2011-07-13 00:00:00.000      07/13/2011
2011-07-12 00:00:00.000      07/12/2011
2011-07-08 00:00:00.000      07/08/2011
2011-05-03 00:00:00.000      05/03/2011
2011-04-28 00:00:00.000      04/28/2011
2011-04-27 00:00:00.000      04/27/2011
2011-04-14 00:00:00.000      04/14/2011
2011-04-07 00:00:00.000      04/07/2011
2011-04-01 00:00:00.000      04/01/2011
2011-03-29 00:00:00.000      03/29/2011

The query is self explanatory; I have converted the registered_date column into varchar and then again into datetime to get the distinct date and this first column is very important in this scenario which look extra in first sight because using this first extra column i was able to sort the date :).

So that’s it.
I Love your feedback


0 comments: