Sub topic 12
Companion Functions: LAST_DAY, NEXT_DAY, and TRUNC with Format Models
This chapter assumes you know the DATE type and its time component, SYSDATE, day arithmetic, plain TRUNC(date), ADD_MONTHS, and MONTHS_BETWEEN. The three functions here fill the gaps those tools leave. They find month boundaries, find the next occurrence of a weekday, and snap a date to the start of a week, month, quarter, or year.
What each function does
| Function | Returns | Time of day |
|---|---|---|
| `LAST_DAY(d)` | The last day of the month containing `d` | Kept from `d` |
| `NEXT_DAY(d, 'WEEKDAY')` | The first given weekday strictly after `d` | Kept from `d` |
| `TRUNC(d, fmt)` | `d` rounded down to the unit named by `fmt` | Set to the start of the unit |
The "time of day" column matters most. LAST_DAY and NEXT_DAY shift the date part only. TRUNC with a format model is the one that clears time. Most bugs with these functions come from forgetting this.
LAST_DAY
LAST_DAY takes one date and returns the final day of its month. It accounts for leap years, so you never need a table of month lengths.
SELECT TO_CHAR(LAST_DAY(DATE '2024-02-10'), 'YYYY-MM-DD') AS leap_february,
TO_CHAR(LAST_DAY(DATE '2025-02-10'), 'YYYY-MM-DD') AS normal_february,
TO_CHAR(LAST_DAY(DATE '2024-04-30'), 'YYYY-MM-DD') AS already_last_day,
TO_CHAR(LAST_DAY(TO_DATE('2024-02-10 14:30:00', 'YYYY-MM-DD HH24:MI:SS')),
'YYYY-MM-DD HH24:MI:SS') AS time_is_kept
FROM dual;| Column | Result |
|---|---|
| `leap_february` | 2024-02-29 |
| `normal_february` | 2025-02-28 |
| `already_last_day` | 2024-04-30 |
| `time_is_kept` | 2024-02-29 14:30:00 |
The last column shows the trap. If your input has a time, the output has the same time. Comparing LAST_DAY(x) to a midnight date can therefore fail even when the day is right. Wrap it as TRUNC(LAST_DAY(x)) when you need a clean day.
Useful month-boundary idioms
- First day of the next month:
LAST_DAY(d) + 1. The result carries the time fromd. - First day of the current month:
TRUNC(d, 'MM'). - Last day of the previous month:
TRUNC(d, 'MM') - 1. - Days left in the month after
d:TRUNC(LAST_DAY(d)) - TRUNC(d).
SELECT TRUNC(LAST_DAY(DATE '2024-03-15')) - TRUNC(DATE '2024-03-15') AS days_left,
TO_CHAR(TRUNC(DATE '2024-03-15', 'MM') - 1, 'YYYY-MM-DD') AS prev_month_end
FROM dual;This returns 16 and 2024-02-29.
LAST_DAY and ADD_MONTHS together
ADD_MONTHS already handles month ends, but sometimes you want the end of a month regardless of the input day. Combine them:
SELECT TO_CHAR(LAST_DAY(ADD_MONTHS(DATE '2024-01-10', 1)), 'YYYY-MM-DD') AS next_month_end
FROM dual;The result is 2024-02-29. Without LAST_DAY, ADD_MONTHS would give 2024-02-10.
NEXT_DAY
NEXT_DAY(d, 'FRIDAY') returns the first Friday that is after d. If d is itself a Friday, you get the Friday one week later. The date 2024-03-15 is a Friday.
SELECT TO_CHAR(NEXT_DAY(DATE '2024-03-15', 'MONDAY'), 'YYYY-MM-DD') AS next_monday,
TO_CHAR(NEXT_DAY(DATE '2024-03-15', 'FRIDAY'), 'YYYY-MM-DD') AS next_friday,
TO_CHAR(NEXT_DAY(DATE '2024-03-15' - 1, 'FRIDAY'), 'YYYY-MM-DD') AS friday_on_or_after,
TO_CHAR(NEXT_DAY(DATE '2024-03-15' - 7, 'MONDAY'), 'YYYY-MM-DD') AS monday_before
FROM dual;| Column | Result | Why |
|---|---|---|
| `next_monday` | 2024-03-18 | Next Monday after the 15th |
| `next_friday` | 2024-03-22 | Strictly after, so not the 15th |
| `friday_on_or_after` | 2024-03-15 | Step back one day, then find the next Friday |
| `monday_before` | 2024-03-11 | Step back one week, then find the next Monday |
The two shifted forms are standard idioms because NEXT_DAY only looks forward. To include the starting day, subtract 1 first. To look backward, subtract 7 first.
Language dependence
The weekday name is read using the session's NLS_DATE_LANGUAGE. 'MONDAY' works in an English session but raises an error such as ORA-01846 (not a valid day of the week) in a German one, where the name is 'MONTAG'. Code that runs in sessions with different settings should not depend on a bare name. You can pin the language for the session:
ALTER SESSION SET NLS_DATE_LANGUAGE = 'AMERICAN';For code that must run unchanged anywhere, prefer TRUNC(d, 'IW') plus an offset (see below). It does not use weekday names.
TRUNC with format models
You know TRUNC(d) removes the time. The second argument is a format model that picks the unit to round down to. Everything smaller than that unit is reset to its minimum: the time becomes midnight, and smaller calendar parts become their first value.
| Format | Truncates to | Result for 2024-03-15 14:30 |
|---|---|---|
| `'DD'` (default) | Start of the day | 2024-03-15 00:00 |
| `'HH24'` | Start of the hour | 2024-03-15 14:00 |
| `'MI'` | Start of the minute | 2024-03-15 14:30 |
| `'IW'` | Monday of the ISO week | 2024-03-11 |
| `'DAY'` | First day of the week, set by the territory | 2024-03-10 in the US (Sunday) |
| `'MM'` | First day of the month | 2024-03-01 |
| `'Q'` | First day of the quarter | 2024-01-01 |
| `'YYYY'` | First day of the year | 2024-01-01 |
Run it yourself:
WITH t AS (
SELECT TO_DATE('2024-03-15 14:30:00', 'YYYY-MM-DD HH24:MI:SS') AS d FROM dual
)
SELECT TO_CHAR(TRUNC(d, 'HH24'), 'YYYY-MM-DD HH24:MI') AS hour_start,
TO_CHAR(TRUNC(d, 'IW'), 'YYYY-MM-DD') AS iso_week_start,
TO_CHAR(TRUNC(d, 'MM'), 'YYYY-MM-DD') AS month_start,
TO_CHAR(TRUNC(d, 'Q'), 'YYYY-MM-DD') AS quarter_start,
TO_CHAR(TRUNC(d, 'YYYY'), 'YYYY-MM-DD') AS year_start
FROM t;Choosing a week start
Two week formats look similar but behave differently:
'IW'always starts the week on Monday (ISO 8601). Its result does not depend on session settings.'DAY'(and'D') starts the week on the day set byNLS_TERRITORY. That is Sunday for the United States and Monday for most of Europe. The same query can return different dates in different sessions.
For reports that must be reproducible, use 'IW'. Two other formats, 'WW' and 'W', are not calendar weeks. 'WW' returns the date that falls on the same weekday as January 1st, and 'W' does the same relative to the first of the month. They rarely give what people expect from "start of week".
Grouping by period
TRUNC with a format is the usual way to bucket rows by month or week:
SELECT TRUNC(order_date, 'MM') AS order_month,
COUNT(*) AS order_count
FROM orders
GROUP BY TRUNC(order_date, 'MM')
ORDER BY order_month;Filtering: keep the column bare
Do not write WHERE TRUNC(order_date, 'MM') = DATE '2024-03-01'. A function on the column stops a normal index on order_date from being used. Compare the bare column against computed boundaries instead:
SELECT order_id, order_date
FROM orders
WHERE order_date >= DATE '2024-03-01'
AND order_date < ADD_MONTHS(DATE '2024-03-01', 1);This half-open range (start included, end excluded) is correct for any time of day. It also avoids the "last moment of the month" problem. Writing <= LAST_DAY(x) would miss rows after midnight on the last day, and <= LAST_DAY(x) + 1 - 1/86400 is fragile. The same range written from a variable d is >= TRUNC(d, 'MM') and < ADD_MONTHS(TRUNC(d, 'MM'), 1).
Choosing the right function
The diagram maps a goal to the function that usually fits.
Common errors
- Assuming
NEXT_DAYincludes today. It never does. Subtract 1 from the input to include it. - Hard-coding English weekday names in code that runs under other
NLS_DATE_LANGUAGEsettings. - Expecting
LAST_DAYto clear the time. It keeps the time, so equality checks against midnight values can fail. - Using
'DAY'when you mean ISO weeks. The start of the week changes withNLS_TERRITORY. Use'IW'. - Wrapping an indexed column in
TRUNCin aWHEREclause. Compute boundaries on the other side of the comparison. - Passing a string.
LAST_DAY('2024-02-10')relies on implicit conversion andNLS_DATE_FORMAT. Use aDATEliteral orTO_DATEwith an explicit format.
Exercise
Exercise
The date 2024-05-16 is a Thursday. Without running anything, what do these return? (a) NEXTDAY(DATE '2024-05-16', 'THURSDAY') (b) NEXTDAY(DATE '2024-05-16' - 1, 'THURSDAY') (c) TRUNC(DATE '2024-05-16', 'IW') (d) LAST_DAY(DATE '2024-05-16') + 1
Show answer
(a) 2024-05-23, because NEXT_DAY is strictly after the input. (b) 2024-05-16, because subtracting one day makes the input a Wednesday, so the next Thursday is the 16th. (c) 2024-05-13, the Monday of that ISO week. (d) 2024-06-01, the day after May 31.
Exercise
Write a WHERE clause for the table orders(orderid, orderdate) that returns every order placed in the previous calendar month, relative to SYSDATE. It must work when orderdate contains times of day and must not wrap orderdate in a function.
Show answer
WHERE orderdate >= ADDMONTHS(TRUNC(SYSDATE, 'MM'), -1) AND order_date < TRUNC(SYSDATE, 'MM'). The lower bound is the first day of last month at midnight. The upper bound is the first day of this month at midnight and is excluded, so rows from any time on the last day of last month are included.
Exercise
A report must show the Monday on or after a given date d, in any session language. Which expression should you use, and why?
Show answer
TRUNC(d - 1, 'IW') + 7 is wrong, because it gives the Monday after d - 1 only when d is not itself a Monday. Use CASE WHEN d = TRUNC(d, 'IW') THEN TRUNC(d) ELSE TRUNC(d, 'IW') + 7 END. It uses only the ISO week format, which is not language dependent, so it works in every NLSDATELANGUAGE setting.