SELECT TO_DATE(START_UTC_DAY, 'YYYYMMDD')
FROM SOURCETABLE
WHERE TO_DATE(START_UTC_DAY, 'YYYYMMDD') > SysDate - 7
TO_DATE() in the WHERE clause converts the string value with the given format model to a DATE type before comparing it to another DATE value thus avoiding the implicit conversion which caused you the issue. See comments for a better variation.
The message here is avoid implicit conversions.
Explanation:
The error was due to implicit conversion in the WHERE clause, a comparison between two values of different data types.
2.2.8.2 Implicit Data Conversion
- When comparing a character value with a DATE value, Oracle
converts the character data to DATE.
During the conversion, the character value/string literal is evaluated against a date format model that depends on the following setting.
select name, value from v$parameter where name = 'nls_date_format';
In my database it returns,
NAME VALUE
-------------------- --------------------
nls_date_format DD-MON-YY
This setting can be changed at the level of a session and that will produce various results as shown below.
Here are some tests to further explain the behavior using SQL Developer using a new session.
SQL> show parameter nls_date_format;
NAME TYPE VALUE
--------------- ------ ---------
nls_date_format string DD-MON-YY
SQL>
select str from
(select '20200412' as str from dual)
where str <> sysdate;
...
Error report -
ORA-01861: literal does not match format string
SQL>
alter session set nls_date_format = 'ddmmyyyy';
Session altered.
SQL>
SQL> show parameter nls_date_format;
NAME TYPE VALUE
--------------- ------ --------
nls_date_format string ddmmyyyy
SQL>
select str from
(select '20200412' as str from dual)
where str <> sysdate;
...
Error report -
ORA-01843: not a valid month
SQL>
alter session set nls_date_format = 'fxyyyy-mm-dd';
Session altered.
SQL>
SQL> show parameter nls_date_format;
NAME TYPE VALUE
--------------- ------ ------------
nls_date_format string fxyyyy-mm-dd
SQL>
select str from
(select '20200412' as str from dual)
where str <> sysdate;
...
Error report -
ORA-01861: literal does not match format string
SQL>
alter session set nls_date_format = 'yyyymmdd';
Session altered.
SQL>
SQL> show parameter nls_date_format;
NAME TYPE VALUE
--------------- ------ --------
nls_date_format string yyyymmdd
SQL>
select str from
(select '20200412' as str from dual)
where str <> sysdate;
STR
--------
20200412
As shown above, the same query ends up producing different "results" depending on the nls_date_format setting.
START_UTC_DAY? - Wernfried DomscheitDESC SOURCETABLE;and paste the output, or at least the line which hasSTART_UTC_DAYshowing its data type. - Lalit Kumar Bvarcharcolumn? That is a really, really bad idea - a_horse_with_no_name