The TO_DATE( date_string, format_model )
takes two strings as arguments; however, you are passing SYSDATE
(or SYSDATE - 14
) as the first argument which is not a string as it is already a DATE
data type. Oracle tries to be helpful and will implicitly convert the date to a string using the NLS_DATE_FORMAT
session parameter so your query is effectively:
SELECT '1'
FROM DUAL
WHERE TO_DATE( '11-APR-2018', 'DD-MM-YYYY' )
BETWEEN TO_DATE(
TO_CHAR(
SYSDATE - 14,
( SELECT VALUE
FROM NLS_SESSION_PARAMETERS
WHERE PARAMETER = 'NLS_DATE_FORMAT' )
),
'DD-MM-YYYY'
)
AND TO_DATE(
TO_CHAR(
SYSDATE,
( SELECT VALUE
FROM NLS_SESSION_PARAMETERS
WHERE PARAMETER = 'NLS_DATE_FORMAT' )
),
'DD-MM-YYYY'
)
If your NLS_DATE_FORMAT
matches DD-MM-YYYY
then your query will work:
SQL Fiddle
Query 1:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY'
SELECT '1'
FROM DUAL
WHERE TO_DATE( '11-APR-2018', 'DD-MM-YYYY')
BETWEEN TO_DATE( SYSDATE - 14, 'DD-MM-YYYY' )
AND TO_DATE( SYSDATE, 'DD-MM-YYYY' )
Results:
| '1' |
|-----|
| 1 |
However, if your NLS_DATE_FORMAT
does not match then you will almost certainly get an exception since either SYSDATE - 14
or SYSDATE
formatted as MM-DD-YYYY
will have an invalid month when you try to read it in the format DD-MM-YYYY
.
Query 2:
ALTER SESSION SET NLS_DATE_FORMAT = 'MM-DD-YYYY'
SELECT '1'
FROM DUAL
WHERE TO_DATE( '11-APR-2018', 'DD-MM-YYYY')
BETWEEN TO_DATE( SYSDATE - 14, 'DD-MM-YYYY' )
AND TO_DATE( SYSDATE, 'DD-MM-YYYY' )
Results:
ORA-01843: not a valid month
The simplest solution is not to convert dates to dates and to just use the dates directly (and use a DATE
literal where you have a fixed date value):
SELECT '1'
FROM DUAL
WHERE DATE '2018-04-11' BETWEEN SYSDATE - 14 AND SYSDATE;