简体   繁体   中英

Oracle order by date gives different results

Just curious as to why the below two queries would give different results, when the testdate column is of datatype DATE.

select testdate from <table> order by to_date(testdate) desc;

Returns

18-DEC-14
17-DEC-14
14-JUL-14
10-JUL-14

.

select testdate from <table> order by testdate desc;

Returns

13-NOV-13
18-DEC-14
17-DEC-14
14-JUL-14

Why would that November 2013 result appear at the top of the second results when as I say the coumn TESTDATE is of data tyle DATE and to_date() resolves the issueX?

Based on OP's reply via comments, the issue is:

SQL> WITH dates(dt) AS(
  2  SELECT to_date('18-DEC-2014', 'DD-MON-RR') FROM dual UNION ALL
  3  SELECT to_date('17-DEC-2014', 'DD-MON-RR') FROM dual UNION ALL
  4  SELECT to_date('14-JUL-2014', 'DD-MON-RR') FROM dual UNION ALL
  5  SELECT to_date('10-JUL-2014', 'DD-MON-RR') FROM dual UNION ALL
  6  SELECT to_date('13-NOV-3013', 'DD-MON-RR') FROM dual
  7  )
  8  SELECT dt yy_date,
  9    TO_CHAR(dt, 'DD-MON-YYYY') yyyy_date
 10  FROM dates
 11  ORDER BY dt DESC;

YY_DATE   YYYY_DATE
--------- -----------
13-NOV-13 13-NOV-3013
18-DEC-14 18-DEC-2014
17-DEC-14 17-DEC-2014
14-JUL-14 14-JUL-2014
10-JUL-14 10-JUL-2014

SQL>

Th client is displaying the year as YY due to which year 3013 is displayed as 13 and along with other dates 2014 , it looked as if 2013 is ordered before 2014 in descending order.

Use TO_CHAR to display the date in your desired format, and use TO_DATE to convert a literal into date.

On a side note,

Never use TO_DATE on a DATE , It will implicitly convert it into string and then back to date using locale-specific NLS format.

TO_DATE function expects string to convert it to date with a given format. Providing date column to to_date may result in unexpected behaviour even oracle does not complain about the given input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM