Oracle 在线段收缩(Online Segment Shrink)
Oracle的在线段收缩(Online Segment Shrink)是指在线整理段空间里的碎片,它有以下几个特点:
- 在线,即在段压缩过程中,DML几乎不受影响(只有在结束前很短的时间内,DML会被阻塞)
- in-place的操作,不需要额外的空间
- 收缩完成后索引依然可用
- 压缩段空间
- 调整高水位线
- 释放收回的空间
- 表必须启用row movement
- 表段所在表空间的段空间管理(segment space management)必须为auto
alter table/index/materialized view object_name shrink space [cascade] [compact];
- cascade:是指压缩所有依赖的对象,比如压缩表语句加上cascade,表上所有的索引都会被压缩
- compact:把压缩过程分为两个阶段:第一个阶段的语句带compact,压缩段空间,在这个过程中需要在表上加RX锁,即只在需要移动的行上加锁。由于涉及到rowid的改变,需要enable row movement.同时要disable基于rowid的trigger.这一过程对业务影响比较小。;第二个阶段语句不带compact,调整高水位并释放收回的空间。此过程需要在表上加X锁,会造成表上的所有DML语句阻塞。在业务特别繁忙的系统上可能造成比较大的影响。对于大表,建议采用compact选项。
SYS@TEST16>create table t as select * from dba_objects;
Table created.
SYS@TEST16>create index i on t(object_id);
Index created.
查看表和索引的空间使用情况:
SYS@TEST16>select segment_name,segment_type,bytes,blocks from dba_segments where owner='TEST' and segment_name in
2 (select 'T' from dual UNION ALL select index_name from dba_indexes where table_owner='TEST' and TABLE_NAME='T');
SEGMENT_NAME SEGMENT_TYPE BYTES BLOCKS
------------------------------ ------------------ ---------- ----------
T TABLE 9437184 1152
I INDEX 2097152 256
删除表数据,发现表和索引的空间并没有被收回:
SYS@TEST16>delete from t;
72568 rows deleted.
SYS@TEST16>commit;
Commit complete.
SYS@TEST16>select segment_name,segment_type,bytes,blocks from dba_segments where owner='TEST' and segment_name in
2 (select 'T' from dual UNION ALL select index_name from dba_indexes where table_owner='TEST' and TABLE_NAME='T');
SEGMENT_NAME SEGMENT_TYPE BYTES BLOCKS
------------------------------ ------------------ ---------- ----------
T TABLE 9437184 1152
I INDEX 2097152 256
直到做了段收缩之后,空间才被真正收回:
SYS@TEST16>alter table t enable row movement;
Table altered.
SYS@TEST16>alter table t shrink space cascade compact;
Table altered.
SYS@TEST16>alter table t shrink space cascade;
Table altered.
SYS@TEST16>select segment_name,segment_type,bytes,blocks from dba_segments where owner='TEST' and segment_name in
2 (select 'T' from dual UNION ALL select index_name from dba_indexes where table_owner='TEST' and TABLE_NAME='T');
SEGMENT_NAME SEGMENT_TYPE BYTES BLOCKS
------------------------------ ------------------ ---------- ----------
T TABLE 65536 8
I INDEX 65536 8
推荐阅读: