Click here to Skip to main content
16,016,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have date in varchar format(16/01/2014)..
and i have to order by my data in date format...

when i am using simple order by date..its order by works only in month and date not with year..eg


10/12/2013
31/11/2013
01/01/2014


my query provide this result..how to manage this data with year bases also..like
01/01/2014
10/12/2013
31/11/2013
Posted
Updated 16-Jan-14 6:10am
v2
Comments
Richard MacCutchan 16-Jan-14 13:00pm    
Unfortunately you are doing this wrong. You should use the Date or DateTime type to store dates in a database, not strings.

Convert the varchars to dates (see, for instance "mySQL convert varchar to date" at Stack Overflow[^]) before ordering.
 
Share this answer
 
Comments
Maciej Los 16-Jan-14 15:20pm    
+5!
CPallini 16-Jan-14 15:27pm    
Thank you. However, have a look at skydger's solutions (3 different ones!).
There are several way to achieve your goal
1. Convert your string to date[time]
SQL
SELECT `date_column`
  FROM `your_table`
 ORDER BY str_to_date(`date_column`, '%d/%m/%Y') DESC

2. Reformat your date string to yyyy-mm-dd (or yyyy/mm/dd etc)
SQL
SELECT `date_column`
  FROM `your_table`
  ... 
 ORDER BY CONCAT_WS('-', SUBSTRING(`date_column`, 7, 4), SUBSTRING(`date_column`, 4, 2), SUBSTRING(`date_column`, 1, 2)) DESC


3. Order by years, months and days separately
SQL
SELECT `date_column`
  FROM `your_table`
  ... 
 ORDER BY CAST(SUBSTRING(`date_column`, 7, 4) AS INT), CAST(SUBSTRING(`date_column`, 4, 2) AS INT), CAST(SUBSTRING(`date_column`, 1, 2)) AS INT) DESC
 
Share this answer
 
Comments
CPallini 16-Jan-14 15:26pm    
5. Five, V.
Maciej Los 16-Jan-14 15:31pm    
Agree!
skydger 17-Jan-14 2:18am    
Thank you! :)
skydger 17-Jan-14 2:17am    
Thank you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900