/*
 * Title  : ts_frag.sql
 * Author : EXADIME LLC
 * Created: 01-Aug-2017
 * Updated: 12-Apr-2018
 * Release: 1.0.0
 * Purpose: This script shows fragmentation at tablespace level.
 * History: N/A
 */

start oracle.ini

set echo off
set feedback off
set serverout on
set termout on

set linesize 250
set pagesize 200
set pause off
set long 80

set heading on
set headsep on
set underline on
set colsep " "

set define on
set verify off
set escape off
set embedded on

column "#"			format 999
column "Tablespace Name"	format a30
column "Total"			format 999,999,999	heading "Blocks|Total"
column "Free"			format 999,999,999
column "Pieces"			format 999,999,999
column "Biggest"		format 999,999,999
column "Smallest"		format 999,999,999
column "Average"		format 999,999,999
column "Dead"			format 999,999,999
column "Frag"			format 99.99		heading "%|Frag"

compute sum of "Total"		on report
compute sum of "Free"		on report
compute sum of "Pieces"		on report
compute sum of "Biggest"	on report
compute sum of "Smallest"	on report
compute sum of "Average"	on report
compute sum of "Dead"		on report

break on report

accept p_order char prompt "Enter order by column {1|2|3|4|5|6|7|8|9|10} [asc|desc] " default 10

spool &&rpt_dir/ts_frag.rpt

select
	row_number() over(order by &&p_order) "#",
	ts.tablespace_name 	"Tablespace Name",
	tf.blocks 		"Total",
	sum(f.blocks)		"Free",
	count(*)		"Pieces",
	max(f.blocks)		"Biggest",
	min(f.blocks)		"Smallest",
	round(avg(f.blocks))	"Average",
	sum(
		decode(
			sign(f.blocks-5),
			-1,
			f.blocks,
			0
		)
	)			"Dead",
	round(
		(
			(
				sum(f.blocks)-max(f.blocks)
			)/sum(f.blocks)
		)*100,2
	)			"Frag"
from   
	dba_free_space f,
	dba_data_files tf,
	dba_tablespaces ts
where  
	ts.tablespace_name=f.tablespace_name
and	ts.tablespace_name=tf.tablespace_name
group by 
	ts.tablespace_name,tf.blocks
order by
	&&p_order
/

spool off

clear columns

set embedded off
set escape off
set verify on
set define on

set colsep " "
set underline on
set headsep on
set heading on

set pause off
set pagesize 24
set linesize 80
set long 80

set termout on
set serverout off
set feedback on
set echo off
