Sub topic 5
Dropping the Time Portion with TRUNC
Prerequisites: you should know basic SELECT queries, the WHERE clause, the DUAL table, and Oracle numeric and character data types.
Oracle's DATE data type stores both a calendar date and a time. For example, one value can represent 2024-06-15 14:30:00. The time is stored even when a query displays only the date.
TRUNC removes the time portion from a DATE. It returns a new DATE set to midnight, which is 00:00:00.
Using TRUNC with dates
The simplest form is TRUNC(date_value):
SELECT SYSDATE AS current_value,
TRUNC(SYSDATE) AS today_at_midnight,
TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS current_text,
TO_CHAR(TRUNC(SYSDATE), 'YYYY-MM-DD HH24:MI:SS') AS truncated_text
FROM dual;The result depends on the database server's clock, but the two formatted values will show different times:
| Expression | Meaning |
|---|---|
| `SYSDATE` | Current date and time from the database server |
| `TRUNC(SYSDATE)` | Current date at midnight |
| `TRUNC(date_column)` | The value of `date_column` with its time removed |
TRUNC does not change the stored value in a table. It only changes the value returned by that expression. It also does not round. A value at 23:59:59 becomes midnight on the same date, not midnight on the next date.
Comparing dates by calendar day
Suppose you want every row created today, regardless of its time. A direct comparison with SYSDATE usually fails because the stored time must match the current time exactly.
You can compare the truncated values:
SELECT order_id, order_date
FROM orders
WHERE TRUNC(order_date) = TRUNC(SYSDATE);This is easy to read, but applying TRUNC to the column can prevent Oracle from using a normal index on order_date efficiently. A half-open range is usually better:
SELECT order_id, order_date
FROM orders
WHERE order_date >= TRUNC(SYSDATE)
AND order_date < TRUNC(SYSDATE) + 1;The first boundary includes midnight at the start of today. The second boundary excludes midnight at the start of tomorrow. This includes every time today, including values close to 23:59:59.
TRUNC format models
You can pass a format model to truncate at a larger calendar unit. TRUNC(date_value, 'MM') returns the first day of the month at midnight. TRUNC(date_value, 'YYYY') returns the first day of the year at midnight.
SELECT TRUNC(DATE '2024-06-15', 'DD') AS day_start,
TRUNC(DATE '2024-06-15', 'MM') AS month_start,
TRUNC(DATE '2024-06-15', 'YYYY') AS year_start
FROM dual;TRUNC(date_value, 'IW') truncates to the Monday that starts the ISO week. Week-based calculations can differ from calculations based on a Sunday-starting week, so choose the format model deliberately.
Exercise
Write a condition that returns rows from event_time occurring during the month containing SYSDATE, without applying a function to event_time.
Show answer
Use event_time >= TRUNC(SYSDATE, 'MM') AND event_time < ADD_MONTHS(TRUNC(SYSDATE, 'MM'), 1).