Sub topic 1
What an Oracle DATE Really Stores
Oracle's DATE type holds a date and a time of day. Each value stores the century, year, month, day, hour, minute, and second. It has no fractional seconds and no time zone. TIMESTAMP differs here: it can store fractional seconds, and its TIME ZONE variants also store a time zone offset.
Prerequisites
This chapter assumes you can write basic SELECT queries with a WHERE clause and that you have seen the DUAL table. Every example runs against DUAL.
Writing and displaying dates safely
Write dates with a date literal or with TODATE and an explicit format mask. Do not depend on the NLSDATE_FORMAT setting, because it can differ between sessions.
SELECT DATE '2024-03-01' AS literal_date,
TO_DATE('01-03-2024', 'DD-MM-YYYY') AS explicit_date,
TO_CHAR(DATE '2024-03-01', 'DD Mon YYYY') AS shown
FROM dual;Use TO_CHAR to control how a date appears in output. Avoid comparing a date to a string, because Oracle converts the string using the session format.
Getting the current date and time with SYSDATE
SYSDATE returns the current date and time of the database server as a DATE value.
SELECT SYSDATE,
TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS formatted_now
FROM dual;SYSTIMESTAMP returns a TIMESTAMP WITH TIME ZONE value that includes fractional seconds. CURRENT_DATE returns the date in the session's time zone. Choose the function that matches the precision and time zone you need.
Adding and subtracting days
Adding a whole number to a DATE adds days. Adding a fraction adds part of a day, so 1/24 adds one hour. Subtracting one DATE from another returns the number of days between them.
SELECT TRUNC(SYSDATE) + 1 AS tomorrow_midnight,
SYSDATE + 1/24 AS in_one_hour,
DATE '2024-03-01' - DATE '2024-02-01' AS days_between
FROM dual;Exercise
What does DATE '2024-03-01' - DATE '2024-02-01' return, and why?
Show answer
It returns 29. February 2024 is a leap month, so the span from February 1 to March 1 is 29 days.