Sub topic 11
Rolling date windows in WHERE clauses
This chapter assumes you know the DATE type's hidden time component, TRUNC, SYSDATE, day arithmetic, and ADD_MONTHS with its end-of-month rule from earlier chapters. It puts them together into filters such as "the last three months" that return the right rows and still let Oracle use an index.
Why windows go wrong
A rolling window is a range whose edges move with the current date, such as "the last 30 days" or "the last three months". Most mistakes come from two facts:
- Every DATE column carries a time of day. A value shown as
2024-06-10may really be2024-06-10 15:30:00. - SYSDATE also carries a time of day.
order_date <= SYSDATEmeans "up to this exact second", not "up to the end of today".
The reliable approach is to compute both edges as midnight boundaries and treat the range as half-open: include the lower edge, exclude the upper edge.
The half-open pattern
The pattern is column >= start AND column < end. The start is the first instant you want. The end is the first instant you do not want.
SELECT order_id, order_date
FROM orders
WHERE order_date >= ADD_MONTHS(TRUNC(SYSDATE), -3)
AND order_date < TRUNC(SYSDATE) + 1;The pieces work like this:
TRUNC(SYSDATE)is today at 00:00:00.ADD_MONTHS(TRUNC(SYSDATE), -3)is midnight on the same day of the month three months ago, subject to the month-end rule below.TRUNC(SYSDATE) + 1is tomorrow at 00:00:00. Excluding it with<includes every moment of today, whether 00:00:00 or 23:59:59.
Why BETWEEN is a trap
BETWEEN a AND b includes both ends. That suits integers but not values with a time component. The query below uses a fixed "today" of 2024-06-10 so you can run it and get the same result every time.
WITH orders (order_id, order_date) AS (
SELECT 1, TO_DATE('2024-03-10 00:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM dual UNION ALL
SELECT 2, TO_DATE('2024-03-09 23:59:59', 'YYYY-MM-DD HH24:MI:SS') FROM dual UNION ALL
SELECT 3, TO_DATE('2024-06-10 15:30:00', 'YYYY-MM-DD HH24:MI:SS') FROM dual UNION ALL
SELECT 4, TO_DATE('2024-06-11 00:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM dual
),
params AS (
SELECT DATE '2024-06-10' AS today FROM dual
)
SELECT o.order_id,
TO_CHAR(o.order_date, 'YYYY-MM-DD HH24:MI:SS') AS order_date,
CASE WHEN o.order_date BETWEEN ADD_MONTHS(p.today, -3) AND p.today
THEN 'Y' ELSE 'N' END AS naive_between,
CASE WHEN o.order_date >= ADD_MONTHS(p.today, -3)
AND o.order_date < p.today + 1
THEN 'Y' ELSE 'N' END AS half_open
FROM orders o
CROSS JOIN params p
ORDER BY o.order_id;| order_id | order_date | naive_between | half_open |
|---|---|---|---|
| 1 | 2024-03-10 00:00:00 | Y | Y |
| 2 | 2024-03-09 23:59:59 | N | N |
| 3 | 2024-06-10 15:30:00 | N | Y |
| 4 | 2024-06-11 00:00:00 | N | N |
Order 3 happened today, but p.today is midnight, so the afternoon order falls after the BETWEEN upper end and disappears. The half-open version includes it and still excludes order 4, which belongs to tomorrow.
Writing BETWEEN a AND b + 1 - 1/86400 is a common workaround. It stops at 23:59:59 and is wrong for any column that holds fractions of a second, such as a TIMESTAMP. Prefer < b + 1.
Keep the column bare
You might try to avoid the time problem by truncating the column:
-- Works, but usually prevents a normal index on order_date from being used
WHERE TRUNC(order_date) >= ADD_MONTHS(TRUNC(SYSDATE), -3)
AND TRUNC(order_date) <= TRUNC(SYSDATE)This returns the right rows, but it wraps the column in a function. A regular B-tree index on order_date stores the raw values, so the optimizer generally cannot use it for a condition on TRUNC(order_date). In the half-open form the column stands alone and only constants are computed, so an index range scan stays possible.
If you must filter on TRUNC(order_date), create a function-based index on that exact expression.
Common window shapes
Each example below assumes the orders table from earlier.
Today only
WHERE order_date >= TRUNC(SYSDATE)
AND order_date < TRUNC(SYSDATE) + 1The last N days
"Last 7 days" is ambiguous, so decide which meaning you want:
- Seven full days ending now (a rolling 168 hours):
order_date >= SYSDATE - 7. - Today plus the six previous calendar days:
order_date >= TRUNC(SYSDATE) - 6 AND order_date < TRUNC(SYSDATE) + 1. - The seven complete days before today:
order_date >= TRUNC(SYSDATE) - 7 AND order_date < TRUNC(SYSDATE).
Because the first form starts at the current time of day, its start moves every second. Reports run at 09:00 and at 17:00 return different rows for the oldest day. That is correct for "the last 168 hours" and surprising for "the last week".
The last N hours
WHERE order_date >= SYSDATE - 6/24Here you want the time of day, so you do not truncate.
Month to date
WHERE order_date >= TRUNC(SYSDATE, 'MM')
AND order_date < TRUNC(SYSDATE) + 1TRUNC(SYSDATE, 'MM') returns the first day of the current month at midnight. A later chapter covers format models; for now, treat it as "start of this month".
The previous complete calendar month
WHERE order_date >= ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -1)
AND order_date < TRUNC(SYSDATE, 'MM')This is the best case for the half-open pattern. You never need to know whether the month has 28, 29, 30, or 31 days, because the upper bound is simply the first instant of this month. Starting from the first of a month also avoids every month-end problem, because day 1 always exists.
Month-end behavior at the window edge
When the start of the window is calculated from today's date with ADD_MONTHS, the month-end rule applies. Two cases matter:
- The day does not exist in the target month.
ADD_MONTHS(DATE '2024-05-30', -3)asks for February 30, so you get 2024-02-29. - Today is the last day of its month. Oracle returns the last day of the target month, even when the target month is longer.
ADD_MONTHS(DATE '2024-02-29', -3)returns 2023-11-30, not 2023-11-29.
The second case produces a window that is one day wider than you might expect. On 29 February, "the last three months" starts on 30 November, not 29 November. On the other side, ADD_MONTHS(DATE '2024-08-31', -6) returns 2024-02-29, because Aug 31 is a month's last day.
| Today | Expression | Window starts |
|---|---|---|
| 2024-06-10 | `ADD_MONTHS(TRUNC(SYSDATE), -3)` | 2024-03-10 |
| 2024-05-31 | `ADD_MONTHS(TRUNC(SYSDATE), -3)` | 2024-02-29 |
| 2024-02-29 | `ADD_MONTHS(TRUNC(SYSDATE), -3)` | 2023-11-30 |
For most reports this behavior is acceptable and consistent. If you need stricter semantics, such as "exactly 90 days", use day arithmetic instead: TRUNC(SYSDATE) - 90. Choose one rule and document it, so two reports built from the same window agree.
Bind variables and user-supplied dates
When a user picks a start and end date, treat the end date as inclusive in the interface and convert it to an exclusive bound in SQL:
SELECT order_id, order_date
FROM orders
WHERE order_date >= TO_DATE(:start_date, 'YYYY-MM-DD')
AND order_date < TO_DATE(:end_date, 'YYYY-MM-DD') + 1;Always give TODATE an explicit format model. Without one, Oracle uses the session's NLSDATE_FORMAT, and the same query can fail or silently read the wrong day in a different session. If the input comes from a date picker that already supplies a DATE, skip the conversion and keep the + 1.
Checklist of common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Today's rows are missing | `<= TRUNC(SYSDATE)` or `BETWEEN ... AND TRUNC(SYSDATE)` | Use `< TRUNC(SYSDATE) + 1` |
| Boundary row appears in two adjacent reports | Both ends inclusive | Use `>=` and `<` consistently |
| Query is slow after "fixing" time | `TRUNC(column)` blocks the index | Move TRUNC to the constants |
| Results change between morning and evening | Window starts at `SYSDATE - N` | Start from `TRUNC(SYSDATE)` |
| Wrong day parsed from text | TO_DATE without a format model | Specify the format |
| Window is a day wider at month end | ADD_MONTHS last-day rule | Accept it, or use day arithmetic |
SYSDATE is the database server's clock and time zone. If your application or users sit in a different time zone, "today" for them may be a different day from SYSDATE's today. In that case, base the window on a value that matches the business's time zone, such as the session's CURRENT_DATE, and decide that on purpose.
Exercise
A report runs with the filter order_date BETWEEN ADD_MONTHS(TRUNC(SYSDATE), -1) AND TRUNC(SYSDATE). Users complain that orders placed today never appear. Why does this happen, and how would you rewrite the filter?
Show answer
TRUNC(SYSDATE) is today at 00:00:00, and BETWEEN includes only values up to and including that instant. An order placed today at 10:15 is later than the upper bound, so it is excluded. Rewrite it as order_date >= ADD_MONTHS(TRUNC(SYSDATE), -1) AND order_date < TRUNC(SYSDATE) + 1.
Exercise
Today is 2024-08-31 at 13:00. For the filter order_date >= ADD_MONTHS(TRUNC(SYSDATE), -6) AND order_date < TRUNC(SYSDATE) + 1, what are the exact lower and upper bounds?
Show answer
The lower bound is 2024-02-29 00:00:00. August 31 is the last day of its month, so ADD_MONTHS returns the last day of February 2024, which is the 29th in a leap year. The upper bound is 2024-09-01 00:00:00, and it is excluded.
Exercise
Write a WHERE clause that returns orders from the previous complete calendar month, whatever day it is today, without TRUNC on the column.
Show answer
WHERE order_date >= ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -1) AND order_date < TRUNC(SYSDATE, 'MM'). The lower bound is midnight on the first day of last month. The upper bound is midnight on the first day of this month and is excluded, so you never need to know how many days last month had.