56

Can you please help me in solving this problem. I am trying to order the results of an SQL query by date, but I'm not getting the results I need.

The query I'm using is:

SELECT date FROM tbemp ORDER BY date ASC

Results are:

01/02/2009
03/01/2009
04/06/2009
05/03/2009
06/12/2008
07/02/2009

Results should be:

06/12/2008
03/01/2009
01/02/2009
07/02/2009

I need to select the date in the format above.

Your help is much appreciated.

3
  • 7
    It's important when you post questions to provide specifics, like what database you're using and what datatype the DATE column is in your table. It makes it easier for people trying to help you; they don't have to guess.
    – Ken White
    Oct 9, 2009 at 20:34
  • 5
    While I know its not really essential to your answer I'd LOVE to hear a GOOD reason why that column isn't a datetime...
    – Achilles
    Oct 9, 2009 at 20:57
  • 4
    ORDER BY id (the auto increment value)
    – tetris
    Nov 8, 2010 at 10:24

12 Answers 12

52

It seems that your date column is not of type datetime but varchar. You have to convert it to datetime when sorting:

select date
from tbemp
order by convert(datetime, date, 103) ASC

style 103 = dd/MM/yyyy (msdn)

2
  • 2
    This won't sort correctly if the current language and date format settings cause interpret aa/bb/cccc as month/day/year, as is the case for most US installations of SQL Server. (I'm assuming from the use of CONVERT that this is T-SQL, so you can specify style 103 as the optional third parameter to CONVERT and override any language or dateformat context.)
    – Steve Kass
    Oct 9, 2009 at 23:50
  • I would love to know how anyone could figure out that these dates were not of datetime but varchar from the information provided. Why should there be fewer results than initially shown, just by changing the field type? Shouldn't there need to be a WHERE clause to reduce the answers returned, if it is giving all of the results, when it should be giving only some of them?
    – vapcguy
    Feb 4, 2015 at 2:08
19

It sounds to me like your column isn't a date column but a text column (varchar/nvarchar etc). You should store it in the database as a date, not a string.

If you have to store it as a string for some reason, store it in a sortable format e.g. yyyy/MM/dd.

As najmeddine shows, you could convert the column on every access, but I would try very hard not to do that. It will make the database do a lot more work - it won't be able to keep appropriate indexes etc. Whenever possible, store the data in a type appropriate to the data itself.

2
  • 3
    @dusoft: It doesn't really matter what separator you use, so long as it's in the right order of significance.
    – Jon Skeet
    Oct 9, 2009 at 20:33
  • @Jon: It's easier to compare two hyphens than two slashes, because you don't have to deal with the angle. :-D
    – Zed
    Oct 9, 2009 at 21:17
16

Unsure what dbms you're using however I'd do it this way in Microsoft SQL:

select      [date]
from        tbemp 
order by    cast([date] as datetime) asc
0
9

this works for me:

SELECT datefield FROM myTable ORDER BY CONVERT(DATE, datefield) ASC

3

Following answer may help you

perform your date ordering by your date identifier but use to_char() function in select clause and use some other identifier in select clause for date

e.g.

SELECT TO_CHAR(DISPDATE1,'DD/MM/YYYY') AS DISPDATE,
SUM(APPLCOUNT) AS APPLIED,
SUM(CONFCOUNT) AS CONFIRMED
FROM
    (
        SELECT COUNT(ID) AS APPLCOUNT,
                   0 AS CONFCOUNT,
                   STUDENT.APPLIED_ON AS DISPDATE1
            FROM STUDENT
            WHERE STUDENT.ID = P_ID
            GROUP BY STUDENT.APPLIED_ON
        UNION
            SELECT 0 AS APPLCOUNT,
                   COUNT(ID) AS CONFCOUNT,
                   STUDENT.CONFIRMED_ON AS DISPDATE1
            FROM STUDENT
            WHERE STUDENT.ID = P_ID
            GROUP BY STUDENT.CONFIRMED_ON
    )
GROUP BY DISPDATE1
ORDER BY DISPDATE1;
1
  • to_char and can other to_date(created_at, 'dd/mm/yyyy hh24:mi:ss') as DISPDATE .. thanks Brushan! Work fine.
    – KingRider
    Jan 4, 2016 at 17:45
3

SELECT CONVERT(char(19), CAST(date AS datetime), 101) as [date]
FROM tbemp ORDER BY convert(datetime, date, 101) ASC

3

Try using this this work for me

select *  from `table_name` ORDER BY STR_TO_DATE(start_date,"%d-%m-%Y") ASC

where start_date is the field name

2

I wanted to edit several events in descendant chonologic order, and I just made a :

select 
TO_CHAR(startdate,'YYYYMMDD') dateorder,
TO_CHAR(startdate,'DD/MM/YYYY') startdate,
...
from ...
...
order by dateorder desc

and it works for me. But surely not adapted for every case... Just hope it'll help someone !

0
1

This may help you in mysql, php.

//your date in any format
$date = $this->input->post('txtCouponExpiry');

$day = (int)substr($date, 3, 2);
$month = (int)substr($date, 0, 2);
$year = (int)substr($date, 7, 4);

$unixTimestamp = mktime(0, 0, 0, $year, $day, $month);

// insert it into database
'date'->$unixTimestamp;

//query for selecting  order by date ASC or DESC
select * from table order_by date asc;
1

try this

Order by Convert(datetime,@date) desc
1

this should work for your date format

order by convert(date, your_column, 104) desc

1

Casting/Converting can result in out of range exceptions that unfortunately are not always as simple as excluding nulls.

A simple alternative method, which avoids the cast, is:

SELECT date
FROM table
ORDER BY YEAR(date), MONTH(date), DAY(date) ASC;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.