If you start with a date but Oracle needs it as a string (for example for displaying the output!) you either use TO_CHAR
, with or without a format model (and a few other parameters as needed), or you don't use anything and Oracle calls TO_CHAR
for you implicitly, with default values for the parameters. The most important, of course, is the date format model. This is a session parameter called nls_date_format
; to see all your nls settings, you can run
select * from v$nls_parameters;
Conversely, if you start with a string but Oracle needs a date (to insert in a column of date data type, for example, or to use in some date computation, etc.), either you use TO_DATE
, with or without a date format model, or Oracle calls it for you - again with the defaults, including nls_date_format
.
Note that some (but not all) front-ends ignore your nls_date_format
and use a setting you find in the user interface. Dumb feature if you ask me, but you just need to know about it.
Also note that timestamp
and date
are different, and they use different nls
parameters for default formatting. And the same with timestamp with time zone
. So if something doesn't seem right, consider the data types carefully.
On my system:
select value from v$nls_parameters where parameter = 'NLS_DATE_FORMAT';
VALUE
----------------------------------------------------------------
dd-MON-yyyy
select sysdate from dual; -- I didn't use `to_char` so Oracle did
SYSDATE
-----------
12-MAR-2021
create table t (dt date);
insert into t (dt) values ('12-OCT-2020'); -- BAD PRACTICE!
select * from t;
DT
-----------
12-OCT-2020
Now, be aware that the implicit conversion posse hunts down developers who abuse implicit conversions. Now that you know how it's done, don't ever do it anywhere that matters (for example in production). It's OK for quickly building up a test case while you are developing a query; exceptionally poor practice in general. Use TO_CHAR
and TO_DATE
as needed and you'll be fine!