Sub topic 3
Two-digit years: RR versus YY
This chapter assumes you know basic SELECT and WHERE syntax, the DATE, NUMBER, and VARCHAR2 types, and the DUAL table.
Two-digit years: RR versus YY
TO_DATE can read a two-digit year. RR and YY read the same two digits differently. RR picks the century relative to the current year. YY always uses the current century.
SELECT TO_CHAR(TO_DATE('01-01-99', 'DD-MM-RR'), 'YYYY') AS rr_year,
TO_CHAR(TO_DATE('01-01-99', 'DD-MM-YY'), 'YYYY') AS yy_year
FROM dual;In 2026, the first column returns 1999 and the second returns 2099. Use four-digit years in new code.
Understanding conversion errors
Three errors appear most often:
- ORA-01722 (invalid number): a non-numeric string reached TO_NUMBER or an implicit number comparison.
- ORA-01843 (not a valid month): the month is outside 1 to 12.
- ORA-01861 (literal does not match format string): the input text does not fit the format model.
SELECT TO_DATE('01-13-2026', 'DD-MM-YYYY') FROM dual; -- ORA-01843
SELECT TO_DATE('28-NOV-2026', 'DD-MM-YYYY') FROM dual; -- ORA-01861A bad value in one row can fail a query that works for most rows, so test conversions against the full data set.
Handling bad input safely
Oracle 12.2 and later can return a fallback value instead of raising an error.
SELECT TO_NUMBER('abc' DEFAULT -1 ON CONVERSION ERROR) AS n,
TO_DATE('31-02-2026' DEFAULT NULL ON CONVERSION ERROR, 'DD-MM-YYYY') AS d,
VALIDATE_CONVERSION('12x' AS NUMBER) AS is_valid
FROM dual;This returns -1, NULL, and 0. VALIDATE_CONVERSION returns 1 for a valid value and 0 for an invalid one.
Conversions in WHERE clauses and index use
Wrapping a column in a function stops a plain index on that column from being used. Convert the constants instead.
-- Avoid: the function on hire_date blocks a normal index
SELECT * FROM employees WHERE TO_CHAR(hire_date, 'YYYY') = '2026';
-- Prefer: a half-open range leaves the column untouched
SELECT * FROM employees
WHERE hire_date >= TO_DATE('2026-01-01', 'YYYY-MM-DD')
AND hire_date < TO_DATE('2027-01-01', 'YYYY-MM-DD');Going further: timestamps
TOTIMESTAMP parses fractional seconds with the FF element. TOCHAR can format them again.
SELECT TO_CHAR(TO_TIMESTAMP('2026-11-28 14:30:15.123456', 'YYYY-MM-DD HH24:MI:SS.FF6'),
'YYYY-MM-DD HH24:MI:SS.FF3') AS ts_text
FROM dual;This returns 2026-11-28 14:30:15.123, with the fraction truncated to three digits.
Exercise
What does TO_DATE('01-01-75', 'DD-MM-RR') return when the current year is 2026, and why?
Show answer
It returns 1975. When the current year is in 2000 to 2049, RR maps 50 to 99 to the 1900s, so 75 becomes 1975.