0

I have a field in table that is varchar(12), however data in that field is a date - 1/1/2016 (I have about 5,000 dates). I've been trying to do an ORDER BY but it doesn't seem to order by the date. How would I go about doing ORDER BY on that field if it's not a DateTIME field??

3
  • 4
    Use the correct datatype and you won't have these problems. Why are you using varchar instead of date? Commented Jun 15, 2016 at 17:04
  • Can you provide the query you are trying? Then you will get the right answer. Commented Jun 15, 2016 at 17:18
  • Select firstName, LastName, ServiceStart, ServiceEnd from TblClients order by ServiceEnd desc. But vercelli answered it already so it's all set. thank you! Commented Jun 15, 2016 at 17:36

2 Answers 2

5

Try:

Order by cast(Field as datetime) 
Sign up to request clarification or add additional context in comments.

1 Comment

@LD16 Glad it helped. Gordon Linoff has a good point. Check his answer also.
3

The conversion of a date such as "1/1/2016" using CAST() depends on localization settings.

Assuming the value is in MM/DD/YYYY format (some countries do use DD/MM/YYYY), then this is more safely written as:

order by convert(datetime, field, 101) 

Then, you run the risk that the conversion may fail, if a field does not exactly match this format. To prevent this error, SQL Server 2012+ offers try_convert().

So, I think the best approach is:

order by try_convert(datetime, field, 101) 

3 Comments

. . . What's 101 ?
It is the silly method that SQL Server used to format dates before introducing format(). It is a magic code, documented at msdn.microsoft.com/en-us/library/ms187928.aspx.
Thankfully I only need this to query important data that is later copied. I'm not making any stored procedures or reusing it in code. thanks tho!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.