9. Dec. 2008

Working with the Oracle Flashback option we can restore the old data using flashback queries. Introduced in Oracle Version 9.2 the “AS OF” clause can be used to:

  • find the old data
  • restore the old data

Mistakenly set the salary of Manager King to a wrong value:

SQL> update emp set sal=4500 where ename=’KING’;
1 row updated.
SQL> commit;
Commit complete.

SQL> select ename, sal from emp where ename=’KING’;
ENAME             SAL
———- ———-
KING             4500

We can query the old value again using the “AS OF” clause and specifying a time interval:

Issuing this query will tell us the correct value as it was existing 15 minutes before.

SELECT ename, sal FROM emp
AS OF TIMESTAMP (SYSTIMESTAMP – INTERVAL ’15’ MINUTE)
WHERE ename = ‘KING’;

ENAME             SAL
———- ———-
KING             5000

Now we can use flashback query as a sub query in an update statement to restore back to the old value. The command is as follows:

update emp
set sal = (
SELECT sal FROM emp
AS OF TIMESTAMP (SYSTIMESTAMP – INTERVAL ’15’ MINUTE) where ename=’KING’)
where ename=’KING’;

In case you are going to use this for testing purposes, you might find it usefully to record the referencing SCN and use flashback query in combination with the recorded SCN.

SQL> select dbms_flashback.get_system_change_number from dual;
GET_SYSTEM_CHANGE_NUMBER
————————
                 4312233

Now changing a value on purpose:

SQL> update emp set sal=4300 where ename=’KING’;
1 row updated.

SQL> commit;
Commit complete.

SQL> select ename, sal from emp where ename=’KING’;
ENAME             SAL
———- ———-
KING             4300

Then you might not know the previous salary of MILLER but you do know the SCN when it refered to the old value and the original value can be updated and restored with flashback query by using the SCN noted prior to the update statement.

Here is the required query:

SELECT ename, sal FROM emp
AS OF SCN 4312233
where ename=’KING’;

ENAME             SAL
———- ———-
KING             4300

And you can restore the old value by updating the row or better you directly restore the old value using the following update with flashback sub query:

update emp
set sal = (
SELECT sal FROM emp
AS OF SCN 4312233 where ename=’KING’)
where ename=’KING’;

No comments yet

No comments yet.

Sorry, the comment form is closed at this time.