/*
 * Title  : ts_free.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 31-Oct-2023
 * Release: 1.0.0
 * Purpose: Shows free space in all permanent tablespaces.
 * History: N/A
 */

start oracle.ini

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

set linesize 150
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 sno       format 9999            heading "#"
column name      format a30             heading "Tablespace Name"
column total     format 999,999,999,999	heading "Total"
column alloc     format 999,999,999,999	heading "Allocated"
column used      format 999,999,999,999	heading "Used"
column free      format 999,999,999,999	heading "Free"
column pct_used  format 999.99		heading "%|Used"
column largest   format 999,999,999,999	heading "KBytes|Largest"

compute sum of total on report
compute sum of alloc on report
compute sum of free  on report
compute sum of used  on report

break on report

accept p_txt char prompt "Enter search string (E.g. DATA): "
accept p_order char prompt "Enter order by column {1|2|3|4|5|6|7|8} [asc|desc] " default 7

spool &&rpt_dir/ts_free.rpt

select
	row_number() over(order by &&p_order)			sno,
	nvl(b.tablespace_name,nvl(a.tablespace_name,'UNKOWN'))	name,
	total_kbytes						total,
	alloc_kbytes						alloc,
	alloc_kbytes-nvl(free_kbytes,0)				used,
	nvl(free_kbytes,0)+(total_kbytes-alloc_kbytes)		free,
	round(((total_kbytes-(nvl(free_kbytes,0)+
	(total_kbytes-alloc_kbytes)))/total_kbytes)*100,2) 	pct_used,
	nvl(largest_kbytes,0) 					largest
from (
	select 
		sum(bytes)/1024 free_kbytes,
		max(bytes)/1024 largest_kbytes,
		tablespace_name
	from  
		sys.dba_free_space
		group by tablespace_name 
) a,
(
	select 
		sum(decode (autoextensible,'YES',maxbytes/1024,bytes/1024)) total_kbytes,
		sum(bytes)/1024 					    alloc_kbytes,
		tablespace_name
	from 
		sys.dba_data_files
		group by tablespace_name
) b,
(
	select
		tablespace_name,
		contents
	from
		sys.dba_tablespaces
) c
where 
	a.tablespace_name (+) = b.tablespace_name
and	b.tablespace_name=c.tablespace_name
and	c.tablespace_name like upper('%&&p_txt%')
order by
	&&p_order
/

spool off

clear columns
clear computes

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
