Skip to content
Advertisement

How to sort Varchar Date in SQL Server 2000

My table schema (table Name Stock)

Field

If Date having datatype is Datetime then SQL Server sorts the date in well/perfect order. See Below Example.

Then result is:

But if I am going to sort the same by casting varchar than it will be ultimately create problem and the problem is it will not sort date by date order as it is now casting in Varchar.

Look at example below:

Then result is:

You can see second query’s result that it will not sort date in order as because it is now not in datetime datatype. It is casting as varchar or you can say it as string.

Now come to the point that:

If I want to sort date which is casting in varchar order by date than how to do it?.

Advertisement

Answer

What you’re doing is converting a varchar to a varchar and then sorting by that… you’re not sorting by date!

This type here is what you convert your value into – you’re converting into a varchar – of course it won’t sort by date then!

Try this instead:

NOW you’re actually converting your varchar column date to a DATETIME value, and sorting on that resulting DATETIME – and now you get the output:

Update: if you need another formatting, you can of course convert your DATETIME again, back into a VARCHAR using CONVERT with a different style:

Read all about what styles are supported in MSDN CAST and CONVERT

and then you get this output:

Just make sure to sort on the DATETIME value! (not on a string representation of your DATETIME)

And as I said: if you store your dates as DATETIME from the beginning, you’ll save yourself a lot of those conversion back and forth!!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement