Sub topic 3
Reading Fractional Month Results
This chapter assumes you can write SELECT queries with a WHERE clause, you know the DUAL table, and you have used SYSDATE and ADD_MONTHS from earlier chapters.
Reading fractional month results
MONTHS_BETWEEN(date1, date2) returns a number. A whole number means both dates fall on the same day of the month. Otherwise, the fraction is the extra days divided by 31. For example, 2024-01-01 to 2024-02-10 gives 1 + 9/31, or about 1.2903.
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;Keep the full value in your query and round only when you display it.
Calculating age and tenure
Divide the whole months by 12 to get completed years. Use MOD for the leftover months.
SELECT TRUNC(MONTHS_BETWEEN(SYSDATE, DATE '1990-06-15') / 12) AS age_years,
MOD(TRUNC(MONTHS_BETWEEN(SYSDATE, DATE '1990-06-15')), 12) AS extra_months
FROM dual;Tenure works the same way. Replace the birth date with a hire date.
Rolling date windows in WHERE clauses
Compare against midnight boundaries. This query returns orders from the last three months, including all of today:
SELECT order_id, order_date
FROM orders
WHERE order_date >= ADD_MONTHS(TRUNC(SYSDATE), -3)
AND order_date < TRUNC(SYSDATE) + 1;> Do not write order_date <= TRUNC(SYSDATE). That condition drops today's orders that have a time after midnight.
Companion functions: LAST_DAY, NEXT_DAY, TRUNC with format models
LASTDAY returns the last day of the month that contains a date. NEXTDAY returns the first matching weekday after a date. TRUNC with a format model rounds a date down to a unit:
| Expression | Result for 2024-05-17 |
|---|---|
| TRUNC(d, 'MM') | 2024-05-01 |
| TRUNC(d, 'Q') | 2024-04-01 |
| LAST_DAY(d) | 2024-05-31 |
Weekday names in NEXT_DAY depend on the session language.
When to use INTERVAL and TIMESTAMP instead
DATE stores no fractional seconds and no time zone. Use TIMESTAMP when you need either one, and SYSTIMESTAMP to read the current value. Use INTERVAL to express a duration such as INTERVAL '3' MONTH. Interval results can differ from ADD_MONTHS at month ends, so test those cases before you switch.
Exercise
What does MONTHS_BETWEEN(DATE '2024-03-31', DATE '2024-02-29') return?
Show answer
1. Both dates are the last day of their month, so Oracle returns a whole number.