-
Notifications
You must be signed in to change notification settings - Fork 113
/
oracle_table_space_for_schema.sql
61 lines (59 loc) · 2.03 KB
/
oracle_table_space_for_schema.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
--
-- Author: Hari Sekhon
-- Date: 2024-10-11 03:24:48 +0300 (Fri, 11 Oct 2024)
--
-- vim:ts=4:sts=4:sw=4:et:filetype=sql
--
-- https///github.com/HariSekhon/SQL-scripts
--
-- License: see accompanying Hari Sekhon LICENSE file
--
-- If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish
--
-- https://www.linkedin.com/in/HariSekhon
--
-- Oracle - Show Tables' Space Used vs Free and Free Percentage in a given Tablespace
--
-- for tables over 20% utilized
--
-- Calculations assume an 8KB block size, which you should verify like this:
--
-- SELECT value FROM v$parameter WHERE name = 'db_block_size';
--
-- Tested on Oracle 19c
SELECT
t.owner,
t.table_name,
-- each block is 8KB, multiply it to GB, round to two decimal places
ROUND(t.blocks * 8 / 1024 / 1024, 2) AS total_gb_from_tables,
-- estimate from segments
ROUND(s.bytes / 1024 / 1024 / 1024, 2) AS total_gb_from_segments,
-- estimate data size from rows vs average row size, round to two decimal places
ROUND(t.num_rows * t.avg_row_len / 1024 / 1024 / 1024, 2) AS actual_data_gb,
-- estimate free space by subtracting the two above calculations
ROUND(((t.blocks * 8 / 1024) - (t.num_rows * t.avg_row_len / 1024 / 1024)) / 1024, 2) AS free_space_gb,
-- calculate free space percentage from the above three calculations
ROUND(
( (t.blocks * 8) - (t.num_rows * t.avg_row_len / 1024) ) /
(t.blocks * 8) * 100, 2) AS free_space_pct,
t.last_analyzed
FROM
dba_tables t
JOIN
dba_segments s
ON
t.owner = s.owner
AND
t.table_name = s.segment_name
WHERE
t.blocks > 0
AND
t.num_rows > 0
AND
-- TUNE: currently only showing tables over 20% utilized
((t.blocks * 8 / 1024) - (t.num_rows * t.avg_row_len / 1024 / 1024)) / (t.blocks * 8 / 1024) > 0.2
AND
t.owner = 'USERS' -- XXX: Change this to your owner schema
ORDER BY
free_space_gb DESC,
total_gb_from_segments DESC;