Sub topic 2
Dropping the time portion with TRUNC
This chapter assumes you can write basic SELECT queries with a WHERE clause, you know the DUAL table, and you have seen SYSDATE. An Oracle DATE always carries a time of day, so a comparison on a date can silently miss rows. TRUNC removes the time, and that makes day-level logic reliable.
Removing the time with TRUNC
TRUNC(date) returns the same date at midnight (00:00:00). Called without a format model, it truncates to the day.
SELECT SYSDATE AS right_now,
TRUNC(SYSDATE) AS today_midnight
FROM dual;Shifting dates with ADD_MONTHS
ADD_MONTHS(date, n) moves a date forward or backward by n whole months. It keeps the day of month when that day exists in the target month.
SELECT ADD_MONTHS(DATE '2024-01-15', 1) AS plus_one_month,
ADD_MONTHS(DATE '2024-03-31', -1) AS minus_one_month
FROM dual;How ADD_MONTHS handles month ends
When the target month is shorter, ADD_MONTHS returns its last day. A date that is already a month end stays a month end.
SELECT ADD_MONTHS(DATE '2024-01-31', 1) AS clamped,
ADD_MONTHS(DATE '2024-02-29', 1) AS last_day_stays_last
FROM dual;This returns 2024-02-29 and 2024-03-31.
> Note: Test month-end logic with a date such as the 31st. Many billing or reporting bugs come from assuming the day of month never changes.
Measuring distance with MONTHS_BETWEEN
MONTHS_BETWEEN(later, earlier) returns a number of months. It returns a whole number when both dates share the same day of month, or when both are month ends. Otherwise it returns a fraction based on a 31-day month.
SELECT MONTHS_BETWEEN(DATE '2024-03-15', DATE '2024-01-15') AS whole_months,
MONTHS_BETWEEN(DATE '2024-02-10', DATE '2024-01-01') AS fractional
FROM dual;The first result is 2. The second is 1 + 9/31, about 1.2903.
Exercise
Exercise
Which value does MONTHS_BETWEEN(DATE '2024-03-31', DATE '2024-02-29') return, and why?
Show answer
It returns 1. Both dates are month ends, so Oracle treats the result as a whole number of months even though the days differ.