对于大型数据库,Oracle占用的磁盘空间非常大,掌握数据库中那些用户、表占用了多杀磁盘空间,以及增长情况,可以方便日后对磁盘系统进行维护和扩充。
对Oracle磁盘空间使用情况,可以分为按照表空间、用户或者表来进行统计。
(一)、表空间
计算表空间的剩余大小
select A.TABLESPACE_NAME,A.BYTES/(1024*1024*1024) "SPACE(G)", C.BYTES/(1024*1024) "FREE SPACE(M)",(C.BYTES*100)/A.BYTES "% FREE" FROM SYS.SM$TS_AVAIL A,SYS.SM$TS_FREE C WHERE A.TABLESPACE_NAME=C.TABLESPACE_NAME;
或者
select tablespace_name, sum(bytes)/(1024*1024*1024) "SPACE(G)" from dba_free_space group by tablespace_name;
(二)、用户
计算每个用户占用的磁盘空间
select owner,sum(bytes)/1024/1024/1024 "Space(G)" from dba_segments group by owner order by 2;
计算某个用户占用的磁盘空间
select owner,sum(bytes)/1024/1024/1024 "Space(G)" from dba_segments where owner=‘LIAOJL‘ group by owner;
(三)、表
Oracle都是以段为存储的,segment_name包含了表、索引、回滚段等,所以在dba_extents,dba_segments都可以找到占用空间大小的信息。
select sum(bytes)/1024/1024 "Space(M)" from dba_extents where owner=‘LIAOJL‘ and segment_name=‘STUDENTS‘;
dba_segments也可以计算表的大小:
select segment_name,bytes/1024/1024 "Space(MB)" from dba_segments where SEGMENT_TYPE=‘TABLE‘ and segment_name=upper(‘你要查找的表的名字‘);
当时上面的写法不完全正确,当表是分区表,dba_segments有多条信息,可改成:
select segment_name,sum(bytes)/1024/1024 "Space(MB)" from dba_segments where segment_name=upper(‘你要查找的表的名字‘);
上述方法对于一个很大的数据库,SQL语句执行起来会很慢,而且消耗数据库资源。Oracle支持对表进行分析,执行分析表操作后可以在dba_tables等系统表中查询表大小、行数等信息,不过这些信息不是实时更新的,可以在数据库空闲时,通过计划任务来更新。
分析SQL方法:
analyze table tab_name compute statistics;
表太大的话可以执行:
analyze table tab_name estimate statistics;
/*SELECT tablespace_name, sum ( blocks ) as free_blk ,
trunc ( sum ( bytes ) /(1024*1024) ) as free_m,
max ( bytes ) / (1024) as big_chunk_k, count (*) as num_chunks
FROM dba_free_space GROUP BY tablespace_name;*/
/*
* SqlName: obj_seg
* 2006-11-17 By HuiYi
* 查詢對象大小
*/
select owner,sum(bytes)/1024/1024/1024 "Space(G)" from dba_segments group by owner order by 2 desc
col segment_name format a30
col segment_type format a15
col tablespace_name format a10
col bytes heading "Size(M)"
with t as(
select segment_name,owner,owner||‘.‘||segment_name,
segment_type,
tablespace_name,
bytes / 1024 / 1024 bytes
from dba_segments
where owner = upper(‘&user‘)
order by bytes desc
)
select * from t where rownum<10;