I always get confused with date format in ORACLE SQL query and spend minutes together to google, Can someone explain me the simplest way to tackle when we have different format of date in database table ?
for instance i have a date column as ES_DATE, holds data as 27-APR-12 11.52.48.294030000 AM of Data type TIMESTAMP(6) WITH LOCAL TIME ZONE.
I wrote simple select query to fetch data for that particular day and it returns me nothing. Can someone explain me ?
select * from table
where es_date=TO_DATE('27-APR-12','dd-MON-yy')
or
select * from table where es_date = '27-APR-12';
Oracle date format The standard date format for input and output is DD-MON-YY e.g., 01-JAN-17 which is controlled by the value of the NLS_DATE_FORMAT parameter. The following statement returns the current date with the standard date format by using the SYSDATE function.
To set the date format: Select Preferences in the left frame, or select File, and then Preferences. Click the Planning icon, and then select Display Options. For Date Format, select MM-DD-YYYY, DD-MM-YYYY, YYYY-MM-DD, or Automatically Detect (to use your system's locale settings).
Oracle stores dates in an internal numeric format representing the century, year, month, day, hours, minutes, seconds. The default date format is DD-MON-YY. SYSDATE is a function returning date and time.
to_date()
returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:
select * from table where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')
You probably want to create an index on trunc(es_date)
if that is something you are doing on a regular basis.
The literal '27-APR-12'
can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date()
with a proper format mask (or an ANSI literal: date '2012-04-27'
)
Although you did right in using to_date()
and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'
.
With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy')
when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy'
or 'yyyy-mm-dd'
if you are using same date format and have select query where date in oracle :
select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';
To_DATE provided by oracle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With