Sub topic 2
Writing and displaying dates safely
This chapter assumes you can write basic SELECT queries with a WHERE clause, you know the DUAL table, and you have met the idea that a DATE stores both a date and a time of day. Here you will learn how to write date values in SQL, turn strings into dates, turn dates into strings, and control what your session shows. Most "date bugs" in Oracle are conversion bugs, not arithmetic bugs.
A DATE has no display format
A DATE column stores a date and a time as a fixed binary value. It does not store text like 01-MAR-24. Whenever you see a date as text, something converted it, and the conversion followed a format. That format can be one you chose or one you inherited from the session.
There are two directions of conversion:
- String to DATE, using a date literal or
TO_DATE. - DATE to string, using
TO_CHARor the client tool's default display.
The safe habit is to name the format yourself in both directions.
Date and timestamp literals
A date literal is the safest way to write a constant date. It uses the keyword DATE followed by a string in the fixed form YYYY-MM-DD.
SELECT DATE '2024-03-01' AS date_literal,
TIMESTAMP '2024-03-01 14:30:00' AS timestamp_literal,
TO_DATE('2024-03-01 14:30:00',
'YYYY-MM-DD HH24:MI:SS') AS to_date_with_time
FROM dual;Three points about this query:
DATE '2024-03-01'always means midnight at the start of that day. It has no time part you can set.- The literal format does not depend on any session setting. It works the same on every database.
TIMESTAMP '...'is a different data type. It holds fractional seconds. UseTO_DATEwhen you need a DATE with a time of day.
Implicit conversion is the trap
Oracle will convert a string to a date for you if you compare it with a DATE or insert it into a DATE column. It uses the session's NLS_DATE_FORMAT.
SELECT order_id
FROM orders
WHERE order_date = '01-MAR-24';This works only when the session format is something like DD-MON-RR and the language matches the month name. A different session format, a different language, or a different client can produce an error or a wrong answer. Code that works on your laptop then fails in a scheduled job.
TO_DATE and format models
TO_DATE(text, format) reads a string according to a format model. The model is built from elements. These are the ones you will use most:
| Element | Meaning | Example input |
|---|---|---|
| `YYYY` | Four-digit year | `2024` |
| `RR` / `YY` | Two-digit year (rules differ, see below) | `24` |
| `MM` | Month number | `03` |
| `MON` / `MONTH` | Abbreviated or full month name | `MAR` / `MARCH` |
| `DD` | Day of month | `01` |
| `DY` / `DAY` | Abbreviated or full day name | `FRI` / `FRIDAY` |
| `HH24` | Hour, 00 to 23 | `14` |
| `HH` or `HH12` with `AM` | Hour, 01 to 12 | `02 PM` |
| `MI` | Minutes | `30` |
| `SS` | Seconds | `00` |
Month names depend on the language. If your input is English and your session might not be, say so in the third argument:
SELECT TO_DATE('01-MAR-2024', 'DD-MON-YYYY',
'NLS_DATE_LANGUAGE=ENGLISH') AS parsed
FROM dual;What happens to missing parts
If your format leaves out a part, Oracle fills in defaults:
- No time part gives midnight (
00:00:00). - No day gives the first day of the month.
- No year or month gives the current year or month, so
TO_DATE('14:30', 'HH24:MI')returns the first day of the current month at 14:30. That is rarely what you wanted.
Lenient parsing and FX
By default, TO_DATE is forgiving about punctuation. Separators in the string can differ from the format.
SELECT TO_DATE('2024/03/01', 'YYYY-MM-DD') AS lenient_ok
FROM dual;This returns 1 March 2024. Add the FX (format exact) modifier and the string must match the format exactly, including separators and digit counts:
SELECT TO_DATE('2024/03/01', 'FXYYYY-MM-DD') AS strict_fails
FROM dual;This fails with ORA-01861: literal does not match format string. Use FX when you validate input from users or files and want bad data rejected instead of quietly accepted.
Common conversion errors
| Error | Usual cause |
|---|---|
| `ORA-01843: not a valid month` | Month name or number does not fit the format, or the language is wrong |
| `ORA-01861: literal does not match format string` | `FX` is used, or the string has a different shape than the format |
| `ORA-01830: date format picture ends before converting entire input string` | The input has extra characters, such as a time, that the format does not cover |
| `ORA-01847: day of month must be between 1 and last day of month` | A day like 31 in a month that has fewer days |
| `ORA-01858: a non-numeric character was found where a numeric was expected` | Text sits where the format expects digits |
Two-digit years: RR versus YY
A two-digit year is ambiguous, and the two elements resolve it differently. YY always uses the current century. RR picks the century closest to the current year: 00 to 49 map to the current century and 50 to 99 map to the previous one, when the current year is in the range 00 to 49.
SELECT TO_CHAR(TO_DATE('01-01-99', 'DD-MM-RR'), 'YYYY') AS with_rr,
TO_CHAR(TO_DATE('01-01-99', 'DD-MM-YY'), 'YYYY') AS with_yy
FROM dual;In the 2020s this returns 1999 for RR and 2099 for YY. Avoid the question completely and use YYYY in your own code.
TO_CHAR: formatting for display
TO_CHAR(date, format) uses the same format elements and returns text.
SELECT TO_CHAR(DATE '2024-03-05', 'YYYY-MM-DD') AS iso_style,
TO_CHAR(DATE '2024-03-05', 'DD Month YYYY') AS padded,
TO_CHAR(DATE '2024-03-05', 'FMDD Month YYYY') AS trimmed,
TO_CHAR(DATE '2024-03-05', 'FMDay, "the" DD') AS with_text
FROM dual;- The
MonthandDayelements pad to the longest name, sopaddedhas trailing spaces inside the string. TheFM(fill mode) prefix removes the padding and leading zeros, sotrimmedis5 March 2024. - Text in double quotes is copied as is. Without the quotes, letters in the format could be read as elements.
- The capitalization of the element controls the output:
MonthgivesMarch,MONTHgivesMARCH, andmonthgivesmarch.
The MM versus MI mistake
MM is the month and MI is the minute. Mixing them up does not raise an error. It prints the wrong number.
SELECT TO_CHAR(TO_DATE('2024-03-01 14:30:00', 'YYYY-MM-DD HH24:MI:SS'),
'HH24:MM') AS wrong_minutes,
TO_CHAR(TO_DATE('2024-03-01 14:30:00', 'YYYY-MM-DD HH24:MI:SS'),
'HH24:MI') AS right_minutes
FROM dual;The first column shows 14:03, the month, and the second shows 14:30.
Do not compare dates as text
It is tempting to write WHERE TO_CHAR(order_date, 'YYYY-MM-DD') = '2024-03-01'. It returns the right rows, but it applies a function to every row, which prevents Oracle from using a normal index on order_date. It also hides the time component instead of handling it. Compare the column to date boundaries instead:
SELECT order_id, order_date
FROM orders
WHERE order_date >= DATE '2024-03-01'
AND order_date < DATE '2024-03-02';This keeps the column untouched and covers every time during 1 March. A later chapter builds on this pattern for rolling windows.
NLS_DATE_FORMAT: the session's default display
NLS_DATE_FORMAT is a setting that supplies the format whenever Oracle converts a DATE to text or text to a DATE without being given a format. SQL*Plus, SQL Developer, and SQLcl use it to display plain DATE columns. The common default is DD-MON-RR, so a time of day is hidden even though it is stored.
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';
SELECT SYSDATE,
DATE '2024-03-01' AS midnight_date
FROM dual;After the ALTER SESSION, both values show with a time, and the literal appears as 2024-03-01 00:00:00. This is the quickest way to see the time component while you learn. Three things to remember:
- The setting changes only how values look and how implicit conversions behave. It never changes what is stored.
- It lasts for the session. The database default, a client environment variable, or a login script can set it elsewhere, so two people can see the same row differently.
- Applications that fetch dates through a driver, such as JDBC, usually receive a date object and format it themselves, so
NLS_DATE_FORMATdoes not control what they show.
A checklist for safe date handling
- Write constants as
DATE 'YYYY-MM-DD'orTO_DATEwith a full format. - Always use four-digit years (
YYYY) in format models. - Pass
NLS_DATE_LANGUAGEwhen parsing month or day names. - Use
FXwhen invalid input should fail loudly. - Use
TO_CHARonly to present values, not to filter or join. - Keep
HH24:MI:SSstraight:MIfor minutes,MMfor months.
Exercise
In a database where the current year is in the 2020s, what four-digit year does TO_DATE('01-01-99', 'DD-MM-YY') produce, and what changes if you use RR instead of YY?
Show answer
With YY the year is 2099, because YY always uses the current century. With RR the year is 1999, because RR maps two-digit years from 50 to 99 to the previous century when the current year is 00 to 49. Using YYYY with a four-digit input removes the ambiguity.
Exercise
Rewrite this filter so it still returns all orders placed at any time on 1 March 2024 but does not wrap the column in a function: WHERE TOCHAR(orderdate, 'YYYY-MM-DD') = '2024-03-01'
Show answer
WHERE orderdate >= DATE '2024-03-01' AND orderdate < DATE '2024-03-02'. The lower bound is midnight at the start of 1 March, and the upper bound is midnight at the start of 2 March, so every time during 1 March is included and 2 March at midnight is excluded.
Exercise
A report prints TOCHAR(tscol, 'HH24:MM') and shows 14:03 for a row stamped 14:30. What is wrong, and what is the fix?
Show answer
MM is the month element, so the output shows the month (March, 03) instead of the minutes. Use HH24:MI to show minutes.