The TIMESTAMP_TO_SCN function in Oracle SQL is a special function that does the exact opposite of SCN_TO_TIMESTAMP. It takes a TIMESTAMP value as an argument and returns the approximate System Change Number (SCN) associated with that time.
This function is a key component of Oracle's Flashback features, as it allows you to find the "database version" (the SCN) that corresponds to a specific point in time.
What is the TIMESTAMP_TO_SCN Function in Oracle?
The TIMESTAMP_TO_SCN(timestamp) function takes a TIMESTAMP and returns a NUMBER (the SCN).
This is useful for:
- Flashback Queries: Finding the SCN you need to use in a query like
SELECT * FROM my_table AS OF SCN .... - Auditing: Determining the SCN for a known event time, which you can then use to query other "AS OF" data.
Note: The association between a timestamp and an SCN is only stored for a limited time (e.g., a few days), which is controlled by your database's undo retention settings. You cannot use this function to find the SCN for a timestamp that is too old.
TIMESTAMP_TO_SCN Function Syntax
The syntax for TIMESTAMP_TO_SCN is very simple:
TIMESTAMP_TO_SCN(timestamp_value)
Let's break that down:
timestamp_value: TheTIMESTAMPyou want to convert to an SCN.
Oracle TIMESTAMP_TO_SCN Function Examples
Here are two practical examples of how to use TIMESTAMP_TO_SCN.
Example 1: Finding the SCN of a Recent Event with TIMESTAMP_TO_SCN
This example shows how you could find the SCN of a row that was just inserted, assuming the row has a TIMESTAMP column.
Query:
-- First, let's assume a row was just inserted
-- INSERT INTO orders (order_id, order_date, ...)
-- VALUES (5000, SYSTIMESTAMP, ...);
-- COMMIT;
-- Now, let's query that row to find the SCN of its order_date
SELECT
TIMESTAMP_TO_SCN(order_date) AS "Order_SCN"
FROM
orders
WHERE
order_id = 5000;
Result: (The SCN will be a large number that varies on every system)
Order_SCN
------------
574100
Example 2: Finding the SCN for a Specific Past Time with TIMESTAMP_TO_SCN
This example shows how to get the SCN for a specific point in the recent past, which you could then use for a Flashback Query.
Query:
-- What was the SCN 10 minutes ago?
SELECT
TIMESTAMP_TO_SCN(
SYSTIMESTAMP - NUMTODSINTERVAL(10, 'MINUTE')
) AS "SCN_10_Minutes_Ago"
FROM DUAL;
Result: (This SCN could then be used in another query: SELECT * FROM employees AS OF SCN 574050)
SCN_10_Minutes_Ago
------------------
574050
