Following on from my earlier comments about how a truncate works in Oracle, the second oldest question about truncate (and other DDL) appeared on the OTN database forum – “Why isn’t a commit required for DDL?”
Sometimes the answer to “Why” is simply “that’s just the way it is” – and that’s what it is in this case, I think. There may have been some historic reason why Oracle Corp. implemented DDL the way they did (commit any existing transaction the session is running, then auto-commit when complete), but once the code has been around for a few years – and accumulated lots of variations – it can be very difficult to change a historic decision, no matter how silly it may now seem.
This posting isn’t about answering the question “why”, though; it’s about a little script I wrote in 2003 in response to a complaint from someone who wanted to truncate a table in the middle of a transaction without committing the transaction. Don’t ask why – you really shouldn’t be executing DDL as part of a transactional process (though tasks like dropping and recreating indexes as part of a batch process is a reasonable strategy).
So if DDL always commits the current transaction how do you truncate a table without committing ? Easy – use an autonomous transaction. First a couple of tables with a little data, then a little procedure to do my truncate:
create table t1 (n1 number); insert into t1 values(1); create table t2 (n1 number); insert into t2 values(1); create or replace procedure truncate_t1 as pragma autonomous_transaction; begin execute immediate 'truncate table t1'; end; /
Then the code to demonstrate the effect:
prompt ====================================== prompt In this example we end up with no rows prompt in t1 and only the original row in t2, prompt the truncate didn't commit the insert. prompt ====================================== insert into t2 values(2); execute truncate_t1; rollback; select * from t1; select * from t2;
According to my notes, the last time I ran this code was on 126.96.36.199 but I’ve just tested it on 188.8.131.52 and it behaves in exactly the same way.
I’ve only tested the approach with “truncate” and “create table” apparently, and I haven’t made any attempt to see if it’s possible to cause major disruption with cunningly timed concurrent activity; but if you want to experiment you have a mechanism which Oracle could have used to avoid committing the current transaction – and you may be able to find out why it doesn’t, and why DDL is best “auto-committed”.