/*
 * Title  : sho_tab_frag.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 05-Oct-2023
 * Release: 1.0.0
 * Purpose: Shows table fragmentation for the given table.
 * History: N/A
 */

start oracle.ini

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

set linesize 200
set pagesize 0
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 dummy     noprint
column sno       format 9999            heading "#"
column owner     format a30		heading "Owner"
column name      format a30             heading "Name"
column total     format 99,999,999,999  heading "Total"
column used      format 99,999,999,999  heading "Used"
column frag      format 99,999,999,999  heading "KBytes|Fragmentation"
column claim     format 999.99          heading "%|Reclaimable"

accept p_owner char prompt "Enter schema name: "
accept p_table char prompt "Enter table name: "

spool &&rpt_dir/sho_tab_frag.rpt

select 
	row_number() over(order by 1) sno,
	owner,
	name,
	total,
	used,
	frag,
	claim
from (
	select 
		owner,
		table_name name,
		round((blocks*8),2) total,
		round((num_rows*avg_row_len/1024),2) used,
		(round((blocks*8),2) - round((num_rows*avg_row_len/1024),2)) frag, 
		((round((blocks * 8), 2) - round((num_rows * avg_row_len / 1024), 2)) / round((blocks * 8), 2)) * 100 - 10 claim
	from 
		dba_tables
	where 
		owner in upper('&&p_owner')
	and	table_name in upper('&&p_table')
	and	(round((blocks*8),2) > round((num_rows*avg_row_len/1024),2))
	order by 5 desc
) order by
	1
/

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
