Sub topic 5
Dropping the time portion with TRUNC
This chapter assumes you know that an Oracle DATE stores a time of day along with the calendar date. It also assumes you can add days to a DATE and call SYSDATE. Here you will learn how TRUNC removes the time portion, where that helps, and where it hurts.
Why the time portion causes trouble
Every DATE value holds a century, year, month, day, hour, minute, and second. When you write DATE '2024-03-15', the time is set to midnight, 00:00:00. A value stored by an application at 09:45 on the same day is not equal to that literal.
The result is a class of bugs where queries look correct and still miss rows. TRUNC fixes this by setting the time part of a date to midnight.
What TRUNC does with a date
TRUNC(date) returns a DATE for the same calendar day with the time set to 00:00:00. The following query is self-contained, so you can run it as shown.
WITH t AS (
SELECT TO_DATE('2024-03-15 14:30:00', 'YYYY-MM-DD HH24:MI:SS') AS ts
FROM dual
)
SELECT TO_CHAR(ts, 'YYYY-MM-DD HH24:MI:SS') AS original,
TO_CHAR(TRUNC(ts), 'YYYY-MM-DD HH24:MI:SS') AS truncated,
ts - TRUNC(ts) AS fraction_of_day,
ROUND((ts - TRUNC(ts)) * 24, 2) AS hours_into_day
FROM t;The output is:
| ORIGINAL | TRUNCATED | FRACTION_OF_DAY | HOURS_INTO_DAY |
|---|---|---|---|
| 2024-03-15 14:30:00 | 2024-03-15 00:00:00 | .6041666666… | 14.5 |
Two points follow from this output:
TRUNCdoes not change the type. The result is still aDATE. It only has a zero time.ts - TRUNC(ts)gives the elapsed fraction of the day. This is useful when you need only the time of day.
The server always stores the time, so TRUNC changes what the value contains. It is not a display setting. Your tool may hide the time because of NLS_DATE_FORMAT, and a truncated date may look the same as an untruncated one. Use TO_CHAR with an explicit format when you want to see the time.
The equality pitfall
Create a small table to see the problem.
CREATE TABLE orders_demo (
order_id NUMBER PRIMARY KEY,
order_date DATE NOT NULL
);
INSERT INTO orders_demo VALUES (1, TO_DATE('2024-03-15 00:00:00', 'YYYY-MM-DD HH24:MI:SS'));
INSERT INTO orders_demo VALUES (2, TO_DATE('2024-03-15 09:45:00', 'YYYY-MM-DD HH24:MI:SS'));
INSERT INTO orders_demo VALUES (3, TO_DATE('2024-03-15 23:59:59', 'YYYY-MM-DD HH24:MI:SS'));
INSERT INTO orders_demo VALUES (4, TO_DATE('2024-03-16 00:00:00', 'YYYY-MM-DD HH24:MI:SS'));
COMMIT;Orders 1, 2, and 3 were placed on March 15. Now compare four ways to ask for "orders on March 15":
| Filter | Rows returned | Verdict |
|---|---|---|
| `order_date = DATE '2024-03-15'` | 1 | Wrong. Only the midnight row matches. |
| `TRUNC(order_date) = DATE '2024-03-15'` | 1, 2, 3 | Correct. |
| `order_date BETWEEN DATE '2024-03-15' AND DATE '2024-03-15' + 1` | 1, 2, 3, 4 | Wrong. `BETWEEN` includes both ends, so midnight of March 16 is returned. |
| `order_date >= DATE '2024-03-15' AND order_date < DATE '2024-03-16'` | 1, 2, 3 | Correct. |
The BETWEEN version is the most dangerous. It looks right, and it fails only for rows stamped exactly at the next midnight. Those rows are rare enough that the bug can survive testing.
Truncating the column or the boundary
You have two correct ways to write the filter. The first applies TRUNC to the column:
SELECT order_id, order_date
FROM orders_demo
WHERE TRUNC(order_date) = DATE '2024-03-15';The second applies TRUNC to the boundary values, so the column stays untouched. It uses a half-open range: the lower bound is included and the upper bound is excluded.
SELECT order_id, order_date
FROM orders_demo
WHERE order_date >= TRUNC(SYSDATE)
AND order_date < TRUNC(SYSDATE) + 1;This second form returns everything stamped today. Both bounds are midnight values. The upper bound, TRUNC(SYSDATE) + 1, is tomorrow's midnight. Because it is excluded, no row from tomorrow can match.
Which form to choose
Prefer the half-open range on large tables. When you wrap a column in a function, as in TRUNC(order_date), the optimizer can no longer use an ordinary index on order_date for a range scan. The query may then scan the whole table. With the range form, the column stays bare and a normal index can be used.
The TRUNC form is still acceptable in two cases. One is a small table. The other is when you have a function-based index on the same expression:
CREATE INDEX orders_demo_trunc_ix ON orders_demo (TRUNC(order_date));A function-based index works only when your query uses the same expression as the index. Maintaining a second index also costs write performance, so the range form is usually simpler.
Counting calendar days
Subtracting two DATE values returns a number of days, and that number includes the time fractions. This can disagree with what people mean by "how many days apart".
SELECT TO_DATE('2024-03-02 01:00', 'YYYY-MM-DD HH24:MI')
- TO_DATE('2024-03-01 23:00', 'YYYY-MM-DD HH24:MI') AS raw_difference,
TRUNC(TO_DATE('2024-03-02 01:00', 'YYYY-MM-DD HH24:MI'))
- TRUNC(TO_DATE('2024-03-01 23:00', 'YYYY-MM-DD HH24:MI')) AS calendar_days
FROM dual;The raw difference is .0833333… of a day (two hours). The calendar difference is exactly 1, because the two values fall on consecutive dates. Truncate both sides when you want whole calendar days. Truncate neither when you want elapsed time.
If one side is SYSDATE, the same rule applies. TRUNC(SYSDATE) - TRUNC(hire_date) gives whole days regardless of the time of day the query runs. Without TRUNC, the answer changes through the day, and the fraction hides the bug until a report is compared across two runs.
Other TRUNC building blocks
A few expressions come up so often that they are worth memorizing:
- Midnight today:
TRUNC(SYSDATE). - Midnight tomorrow:
TRUNC(SYSDATE) + 1. - The last second of today:
TRUNC(SYSDATE) + 1 - 1/86400. - Noon today:
TRUNC(SYSDATE) + 12/24.
The last expression is a workaround for inclusive upper bounds. It works for DATE columns, which have one-second resolution, but a half-open range avoids the problem altogether. It breaks on TIMESTAMP columns with fractional seconds, where a row at 23:59:59.5 would be missed.
The second argument: format models
TRUNC takes an optional second argument, a format model, that chooses the unit to truncate to. The default is 'DD', which is why TRUNC(date) goes to midnight. For the input 2024-03-15 14:30:45:
| Call | Result |
|---|---|
| `TRUNC(d)` or `TRUNC(d, 'DD')` | 2024-03-15 00:00:00 |
| `TRUNC(d, 'HH24')` | 2024-03-15 14:00:00 |
| `TRUNC(d, 'MI')` | 2024-03-15 14:30:00 |
| `TRUNC(d, 'MM')` | 2024-03-01 00:00:00 |
| `TRUNC(d, 'Q')` | 2024-01-01 00:00:00 |
| `TRUNC(d, 'YYYY')` | 2024-01-01 00:00:00 |
| `TRUNC(d, 'IW')` | 2024-03-11 00:00:00 (Monday of the ISO week) |
The month form pairs well with ADD_MONTHS. It gives you a clean "this month" filter:
SELECT order_id, order_date
FROM orders_demo
WHERE order_date >= TRUNC(SYSDATE, 'MM')
AND order_date < ADD_MONTHS(TRUNC(SYSDATE, 'MM'), 1);The lower bound is the first day of the current month. The upper bound is the first day of the next month, and it is excluded. You never need to know whether the month has 28, 29, 30, or 31 days. A later chapter covers the full list of format models.
Common errors
- Using
=on a column that has times. The query returns only rows stamped exactly at midnight. Use a half-open range orTRUNC(column). - Using
BETWEENwith+ 1. The range includes the next midnight. Use<for the upper bound instead. - Wrapping an indexed column in
TRUNC. This disables a normal index on that column. Truncate the boundary values instead, or create a matching function-based index. - Passing a string to
TRUNC.TRUNC('2024-03-15')depends on implicit conversion and on the session'sNLS_DATE_FORMAT. UseDATE '2024-03-15'orTO_DATEwith an explicit format. - Forgetting that
TRUNCon aTIMESTAMPreturns aDATE.TRUNC(SYSTIMESTAMP)drops fractional seconds and the time zone. That is fine for day boundaries. It is not fine if you later need the time zone. - Mixing time zones.
TRUNC(SYSDATE)uses the database server's clock.TRUNC(CURRENT_DATE)uses the session time zone. Near midnight, the two can name different days.
Summary of the working model
- A
DATEalways has a time. A date-only value is aDATEwhose time is midnight. TRUNC(date)returns midnight of the same day, and the result is still aDATE.- Truncate both sides to count calendar days. Truncate neither to measure elapsed time.
- For filters, truncate the boundary values and leave the column alone.
TRUNC(date, 'MM')and similar format models move the value to the start of a larger unit.
Exercise
The table orders_demo has an index on order_date. Write a query that returns the orders placed yesterday, using a form that can use that index. Then explain why WHERE order_date BETWEEN TRUNC(SYSDATE) - 1 AND TRUNC(SYSDATE) is wrong.
Show answer
Use a half-open range with truncated boundaries: SELECT orderid, orderdate FROM ordersdemo WHERE orderdate >= TRUNC(SYSDATE) - 1 AND orderdate < TRUNC(SYSDATE); The column is left bare, so a normal index on orderdate can be used. The BETWEEN version is wrong because BETWEEN includes both ends. Its upper bound, TRUNC(SYSDATE), is today's midnight, so a row stamped exactly 00:00:00 today would be returned as if it were from yesterday.
Exercise
A report runs at 15:00 and computes SYSDATE - hire_date for an employee hired on 2024-03-01 at 09:00:00 (the column holds the time). The report is meant to show whole calendar days of service and gives a fractional number. Rewrite the expression so it returns a whole number of days.
Show answer
TRUNC(SYSDATE) - TRUNC(hire_date). Truncating both sides removes the time-of-day fractions, so the subtraction counts calendar days and returns a whole number whatever time the report runs.