Oracle数据库表是否需要碎片整理
近日有mysql的朋友问我 Oracle数据库的表是否需要定期进行碎片整理.由于oracle的数据表的存储
不像mysql(innodb)那样使用的聚集组织表(IOT)存放数据,而是使用的是称为堆(HEAP)的方式来存放数据.
数据行被存放到的块是随机的.进行全表扫描的时候读取出来的数据行没有按一定的方式进行排序.所以
ORACLE可以对任意有空闲空间的数据块进行数据插入.
假设我们现在创建一个表,过程如下.
SQL> create table t2 as select * from dba_objects;
Table created.
SQL> exec dbms_stats.gather_table_stats('SYS','T2');
PL/SQL procedure successfully completed.
得到当前的表的数据块,行信息
SQL> select table_name,num_rows,blocks,num_rows/blocks from dba_tables where table_name='T2' and owner='SYS';
TABLE_NAME NUM_ROWS BLOCKS NUM_ROWS/BLOCKS
------------------------------ ---------- ---------- ---------------
T2 90426 1535 59.9094463
当前该表拥有90426行,1535个数据块,平均每个块大概是存放了59行数据.
我们通过如下的PLSQL代码来摸拟随机删除10000条数据;
SQL> declare
i number;
begin
for i in 1..10000 loop
delete from t2 where object_id=round(dbms_random.value(0,90000));
end loop;
commit;
end;
PL/SQL procedure successfully completed.
SQL> exec dbms_stats.gather_table_stats('SYS','T2');
PL/SQL procedure successfully completed.
SQL> select table_name,num_rows,blocks,num_rows/blocks from dba_tables where table_name='T2' and owner='SYS';
TABLE_NAME NUM_ROWS BLOCKS NUM_ROWS/BLOCKS
------------------------------ ---------- ---------- ---------------
T2 81413 1535 53.037785
删除10000行后,表的数据块不发生变化,但是平均每个块是存放53行数据.
现在摸拟随机插入数据
SQL> declare
i number;
begin
for i in 1..10000 loop
insert into t2(OWNER, OBJECT_NAME, SUBOBJECT_NAME, OBJECT_ID, DATA_OBJECT_ID, OBJECT_TYPE, CREATED, LAST_DDL_TIME, TIMESTAMP, STATUS, TEMPORARY,
GENERATED, SECONDARY, NAMESPACE, EDITION_NAME, SHARING, EDITIONABLE, ORACLE_MAINTAINED)
values ('SYS', 'I_COBJ#', null, 30, 30, 'INDEX', to_date('07-07-2014 05:39:01', 'dd-mm-yyyy hh24:mi:ss'), to_date('07-07-2014 05:39:01', 'dd-mm-yyyy
hh24:mi:ss'), '2014-07-07:05:39:01', 'VALID', 'N', 'N', 'N', 4, null, 'NONE', null, 'Y');
end loop;
commit;
end;
PL/SQL procedure successfully completed.
SQL> exec dbms_stats.gather_table_stats('SYS','T2');
PL/SQL procedure successfully completed.
SQL> select table_name,num_rows,blocks,num_rows/blocks from dba_tables where table_name='T2' and owner='SYS';
TABLE_NAME NUM_ROWS BLOCKS NUM_ROWS/BLOCKS
------------------------------ ---------- ---------- ---------------
T2 91413 1535 59.552443
我们看到oracle并没有为这个表新分配数据块,还是使用原来的数据块的空闲空间.当某些块中原来的部分数据行被删除时,
这一部分空间可以被重用,这也是为什么oracle的表不需要进行碎片整理的原因.