Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a result set of all tables in the DB with their disk space usage

Is there a T-SQL query I can run against a database that will provide a list of all tables in that database as well as their current disk space usage? I know I can look at it in SSMS with the "properties" dialog, and I know how to use the sp_spaceused sproc to see it one table at a time but I'd like to evaluate the disk space usage of all of my tables, ordered by highest disk space usage to lowest. We need to cut our DB size down significantly so I'd like to see which tables are the worst offenders.

like image 422
Scott Avatar asked Jan 05 '11 16:01

Scott


People also ask

How do I retrieve all tables in a database?

The easiest way to find all tables in SQL is to query the INFORMATION_SCHEMA views. You do this by specifying the information schema, then the “tables” view. Here's an example. SELECT table_name, table_schema, table_type FROM information_schema.

Which is used to retrieve data from tables?

An SQL SELECT statement retrieves records from a database table according to clauses (for example, FROM and WHERE ) that specify criteria.


2 Answers

create table #Temp (
    name nvarchar(128),
    [rows] char(11),
    reserved varchar(18),
    data varchar(18),
    index_size varchar(18),
    unused varchar(18)
)

insert into #Temp
    exec sp_msforeachtable 'sp_spaceused ''?'''

select * from #Temp order by cast(replace(reserved,' kb','') as int) desc
like image 64
Joe Stefanelli Avatar answered Nov 06 '22 09:11

Joe Stefanelli


sys.allocation_units, look at total_pages. Each rowset (partition of an index) has 3 allocation units (DATA, SLOB and LOB), see Table and Index Organization. Join with sys.partitions to get the object_id and the index_id. Index_id 0is the heap of an unordered table, index id 1 is the clustered index. Every table (index) has at least one partition, if is not partitioned:

select object_name(p.object_id) as [name],
    object_schema_name(p.object_id) as [schema],
    i.name as [index],
    i.type_desc,
    au.type_desc,
    p.partition_number,
    p.rows,
    au.total_pages * 8 as [space (kb)]
from sys.allocation_units au
join sys.partitions p on au.container_id = p.partition_id
join sys.indexes i on p.object_id = i. object_id
    and i.index_id = p.index_id
order by [space (kb)] desc;
like image 45
Remus Rusanu Avatar answered Nov 06 '22 09:11

Remus Rusanu