Sub topic 4
Adding and Subtracting Days in Oracle
Assume you know basic SELECT queries, the WHERE clause, the DUAL table, and numeric expressions. This chapter focuses on arithmetic with Oracle's DATE data type.
The working model
An Oracle DATE stores:
- The date: year, month, and day
- The time: hour, minute, and second
When you add a number to a DATE, Oracle treats the number as a count of days. A fraction represents part of a day.
| Expression | Meaning |
|---|---|
| `order_date + 1` | One day after `order_date` |
| `order_date - 7` | Seven days before `order_date` |
| `order_date + 1/24` | One hour after `order_date` |
| `date_2 - date_1` | Number of days between two dates |
The result of subtracting one DATE from another is a number. It can include a fractional part when the times differ.
SELECT DATE '2024-03-01' - DATE '2024-02-01' AS days_between
FROM dual;The result is 29, because 2024 is a leap year.
Adding and subtracting whole days
Use a positive number to move forward and a negative number to move backward.
SELECT SYSDATE AS current_time,
SYSDATE + 1 AS tomorrow_same_time,
SYSDATE - 7 AS one_week_ago,
SYSDATE + 14 AS two_weeks_from_now
FROM dual;Each result keeps the time of day from SYSDATE. If the current value is 2026-11-28 07:30:00, then SYSDATE + 1 represents 2026-11-29 07:30:00.
To move by part of a day, use a fraction:
SELECT TRUNC(SYSDATE) + 1 AS tomorrow_midnight,
SYSDATE + 1/24 AS one_hour_later,
SYSDATE + 30/1440 AS thirty_minutes_later,
SYSDATE + 1/86400 AS one_second_later
FROM dual;There are 24 hours in a day, 1,440 minutes in a day, and 86,400 seconds in a day.
Subtracting dates
Subtracting two DATE values returns elapsed days, including the time component.
SELECT TO_DATE('2024-03-02 12:00:00', 'YYYY-MM-DD HH24:MI:SS')
- TO_DATE('2024-03-01 06:00:00', 'YYYY-MM-DD HH24:MI:SS')
AS elapsed_days
FROM dual;The result is 1.25: one day and six hours.
You can convert the result to other units:
SELECT (end_time - start_time) AS days_elapsed,
(end_time - start_time) * 24 AS hours_elapsed,
(end_time - start_time) * 1440 AS minutes_elapsed
FROM (
SELECT TO_DATE('2024-03-02 12:00:00', 'YYYY-MM-DD HH24:MI:SS') AS end_time,
TO_DATE('2024-03-01 06:00:00', 'YYYY-MM-DD HH24:MI:SS') AS start_time
FROM dual
);The order matters. start_time - end_time produces -1.25.
Time boundaries
A common requirement is to find rows from today. Since a DATE includes a time, compare against midnight boundaries:
SELECT order_id, order_date
FROM orders
WHERE order_date >= TRUNC(SYSDATE)
AND order_date < TRUNC(SYSDATE) + 1;This includes every time today, up to but not including tomorrow's midnight. The half-open range also avoids accidentally excluding rows later today.
Exercise
What does DATE '2024-03-10' + 2.5 represent?
Show answer
It represents 2024-03-12 12:00:00, because 2.5 days equals two days and twelve hours.