Sub topic 3
Getting the current date and time with SYSDATE
SYSDATE is the function you reach for first when a query depends on "now". This chapter covers what it returns, how it differs from the other current-time functions, and the pitfalls that produce wrong results in reports, defaults, and tests.
This chapter assumes you can write basic SELECT queries with a WHERE clause, you know the DUAL table, and you know that Oracle stores dates internally with a time component (covered in the earlier chapters on the DATE type).
What SYSDATE returns
SYSDATE is a function with no parentheses and no arguments. It returns the current date and time of the operating system on the database server, as a DATE value. A DATE has a resolution of one second, so SYSDATE carries no fractional seconds.
SELECT SYSDATE,
SYSTIMESTAMP,
CURRENT_DATE,
TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS formatted_now
FROM dual;The four columns show four different things:
SYSDATEis aDATEtaken from the database server's clock.SYSTIMESTAMPis aTIMESTAMP WITH TIME ZONEfrom the same server clock, with fractional seconds and the server's UTC offset.CURRENT_DATEis aDATEexpressed in the time zone of your session, not the server.formatted_nowis aVARCHAR2that makes the time-of-day visible.
A common surprise is that the first column seems to contain only a date. That is a display issue, not a storage issue.
Why the time seems to be missing
SQL*Plus, SQL Developer, and many other clients convert a DATE to text using the session's NLS_DATE_FORMAT parameter. The default depends on the NLS_TERRITORY setting. For the common American territory it is DD-MON-RR, which shows no time at all.
The value still has hours, minutes, and seconds. You can check this by changing the format for your session:
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';
SELECT SYSDATE FROM dual;For application code, avoid depending on the session setting. Use an explicit TO_CHAR with a format model, as in the first example, so the output is the same on every machine. The reverse also holds: never compare a DATE to a string and let Oracle convert implicitly. Use a DATE '2024-03-01' literal or TO_DATE with a format.
SYSDATE and its relatives
Oracle has several functions that all mean "now", and they differ in data type and time zone.
| Function | Returns | Time zone used | Fractional seconds |
|---|---|---|---|
| `SYSDATE` | `DATE` | Database server OS | No |
| `SYSTIMESTAMP` | `TIMESTAMP WITH TIME ZONE` | Database server OS | Yes |
| `CURRENT_DATE` | `DATE` | Session time zone | No |
| `CURRENT_TIMESTAMP` | `TIMESTAMP WITH TIME ZONE` | Session time zone | Yes |
| `LOCALTIMESTAMP` | `TIMESTAMP` | Session time zone | Yes |
The split to remember is server clock versus session clock. SYSDATE and SYSTIMESTAMP follow the server. CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP follow the session's TIME_ZONE setting.
You can see the difference by moving your session to another zone:
ALTER SESSION SET TIME_ZONE = 'Asia/Tokyo';
SELECT DBTIMEZONE,
SESSIONTIMEZONE,
TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS server_clock,
TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD HH24:MI:SS') AS session_clock
FROM dual;If the server runs in UTC, session_clock is nine hours ahead of server_clock. DBTIMEZONE is the database's time zone setting and SESSIONTIMEZONE is yours. Neither one changes what SYSDATE returns, because SYSDATE reads the server operating system's clock.
Choosing between them
- Use
SYSDATEfor audit columns, defaults, and "as of the database" logic where every user should see the same clock. - Use
SYSTIMESTAMPwhen you need sub-second precision or the UTC offset. - Use
CURRENT_DATEwhen the answer should depend on where the user is, for example "today" for a user in Tokyo. - Prefer a
TIMESTAMP WITH TIME ZONEdesign if your application serves several time zones. KeepingDATEvalues in many zones loses the zone information.
You can convert between the types when needed. CAST(SYSTIMESTAMP AS DATE) drops the fractional seconds and the zone, and keeps the server's local clock time.
Using SYSDATE in queries and defaults
SYSDATE can appear anywhere an expression is allowed. A frequent use is a column default that stamps each new row:
CREATE TABLE audit_log (
log_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
message VARCHAR2(200) NOT NULL,
created_at DATE DEFAULT SYSDATE NOT NULL
);
INSERT INTO audit_log (message) VALUES ('first entry');
SELECT log_id,
message,
TO_CHAR(created_at, 'YYYY-MM-DD HH24:MI:SS') AS created_at
FROM audit_log;The default is evaluated at insert time, so each row gets the time of its own insert statement.
It also works in filters. This query finds orders from the last three months, up to the end of today:
SELECT order_id, order_date
FROM orders
WHERE order_date >= ADD_MONTHS(TRUNC(SYSDATE), -3)
AND order_date < TRUNC(SYSDATE) + 1;Two details matter here. TRUNC(SYSDATE) is midnight today, so both boundaries are clean. The upper bound uses < against tomorrow's midnight instead of <= SYSDATE, so a row stamped later today is not excluded by accident. Later chapters cover TRUNC and range filters in depth. For now, notice that a bare SYSDATE carries the current time, and that usually matters.
How often is SYSDATE evaluated?
In a plain SQL statement, Oracle evaluates SYSDATE as the statement runs, not once per row for a stable result. For a single query, treat the value as one moment in time. Do not rely on it to order rows or to give each row a distinct stamp. A bulk INSERT ... SELECT that stamps rows with SYSDATE can give many rows the same second.
In PL/SQL, every call is a fresh read of the clock. Two assignments in one procedure can return different values:
SET SERVEROUTPUT ON
DECLARE
v_start DATE := SYSDATE;
v_end DATE;
BEGIN
DBMS_SESSION.SLEEP(2);
v_end := SYSDATE;
DBMS_OUTPUT.PUT_LINE('Elapsed seconds: ' || ROUND((v_end - v_start) * 86400));
END;
/This prints Elapsed seconds: 2. The subtraction yields days, so multiplying by 86,400 (24 × 60 × 60) converts to seconds. DBMS_SESSION.SLEEP is available from Oracle Database 18c. On older releases, use DBMS_LOCK.SLEEP, which needs an extra grant.
If a procedure needs one consistent "now" across several statements, read SYSDATE once into a variable and reuse it.
Gotchas
The time component breaks equality tests
This query usually returns nothing:
SELECT order_id FROM orders WHERE order_date = SYSDATE;SYSDATE has a time down to the second, and a stored order_date almost never matches that exact second. To match "today", compare a range as shown above. Do not wrap the column in TRUNC(order_date) on a large table unless you have a matching function-based index, because that prevents a normal index on order_date from being used.
SYSDATE is not deterministic
Because its value changes, you cannot use SYSDATE in a function-based index, a virtual column, or a check constraint. A constraint such as CHECK (hire_date <= SYSDATE) is rejected. Enforce that rule in a trigger or in application code, and remember it only checks at the time of the change.
Server time zone and daylight saving time
SYSDATE shows local server time, including daylight saving shifts. During a clock change, the same local time can occur twice, or an hour can be skipped. Elapsed-time calculations across that boundary can be off by an hour. If you need an unambiguous record, store SYSTIMESTAMP in a TIMESTAMP WITH TIME ZONE column, or use UTC.
Moving a database changes the meaning
If a database is moved to a server in another zone, SYSDATE changes meaning without any code change. Code that must be stable should not assume a specific server zone.
Testing code that uses SYSDATE
Tests that compare against "today" break the next day. Two practical approaches:
- Pass the reference date in as a parameter, with
SYSDATEas the default (p_as_of DATE DEFAULT SYSDATE), so tests can supply a fixed date. - On a non-production system, an administrator can freeze
SYSDATEwith theFIXED_DATEinitialization parameter, for exampleALTER SYSTEM SET FIXED_DATE = '2024-01-15-10:30:00'. It affects onlySYSDATEand applies to the whole instance, so it is risky outside an isolated test database.
Quick reference
SYSDATEis aDATEread from the server clock, with one-second resolution.SYSTIMESTAMPadds fractional seconds and a time zone offset.CURRENT_DATE,CURRENT_TIMESTAMP, andLOCALTIMESTAMPuse the session time zone.- Display of a
DATEis controlled byNLS_DATE_FORMAT, which hides the time in many default setups. SYSDATEis not deterministic, so it cannot be used in function-based indexes, virtual columns, or check constraints.- For "today", use
TRUNC(SYSDATE)and half-open ranges.
Exercise
A session runs ALTER SESSION SET TIME_ZONE = 'America/New_York' while the database server runs in UTC. Which of SYSDATE and CURRENT_DATE changes its result because of this setting, and why? Also, why does WHERE order_date = SYSDATE almost never match any rows?
Show answer
CURRENT_DATE changes, because it is calculated in the session time zone. SYSDATE still reads the server operating system's clock, so it is unaffected by the session setting. order_date = SYSDATE almost never matches because SYSDATE includes the current time to the second, and a stored order_date would have to equal that exact second. To match a day, use a range such as order_date >= TRUNC(SYSDATE) AND order_date < TRUNC(SYSDATE) + 1.
Exercise
Write a query that returns the number of whole seconds between a variable v_start (a DATE) and the current time, using only DATE arithmetic and no functions other than SYSDATE and ROUND.
Show answer
ROUND((SYSDATE - v_start) * 86400). Subtracting two DATE values returns a number of days, and a day has 86,400 seconds (24 60 60).