/*
 * Title  : temp_free.sql
 * Author : EXADIME LLC
 * Created: 25-Nov-2019
 * Updated: 09-Oct-2021
 * Release: 1.0.0
 * Purpose: Shows free space in all temp tablespaces.
 * History: N/A
 */

start oracle.ini

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

set linesize 125
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 name	 format a30		heading "Tablespace Name"
column total	 format 99,999,999,999	heading "Total"
column alloc	 format 99,999,999,999	heading "Allocated"
column used	 format 99,999,999,999	heading "Used"
column free	 format 99,999,999,999	heading "MBytes|Free"
column pct_used	 format 999.99		heading "%|Used"

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_order char prompt "Enter order by column {1|2|3|4|5|6} [asc|desc] " default 2

spool &&rpt_dir/temp_free.rpt

select
	row_number() over(order by &&p_order)			sno,
	tablespace						name,
	mb_total						total,
	mb_used 						used,
	mb_free							free,
	round((mb_used/mb_total)*100,2) 			pct_used
from (
	select 
		d.name tablespace, 
		nvl(d.mb_total,0)						 mb_total,
		nvl(sum(a.used_blocks * d.block_size)/1024/1024,0)		 mb_used,
		nvl(d.mb_total - sum (a.used_blocks * d.block_size)/1024/1024,0) mb_free
	from 
		v$sort_segment a,
		(
			select 
				b.name, 
				c.block_size, 
				sum (c.bytes)/1024/1024 mb_total
			from 
				v$tablespace b, 
				v$tempfile c
			where 
				b.ts#= c.ts#
			group by 
				b.name, c.block_size
		) d
	where 
		a.tablespace_name(+) = d.name
	group by 
		d.name, d.mb_total
)
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