HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

How to query a database for empty tables

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
tablesqueryemptydatabaseforhow

Problem

Due to some 'developers' we had working on our system we have had issues with empty tables. We have found that during the transfer to the cloud several tables were copied, but the data in them wasn't.

I would like to run a query the system tables to find what user tables are empty. We are using MS SQL 2008 R2.

Thanks for the help.

Solution

Leverage sys.tables and sys.partitions:

select
    t.name table_name,
    s.name schema_name,
    sum(p.rows) total_rows
from
    sys.tables t
    join sys.schemas s on (t.schema_id = s.schema_id)
    join sys.partitions p on (t.object_id = p.object_id)
where p.index_id in (0,1)
group by t.name,s.name
having sum(p.rows) = 0;


Use a sum of rows just to make sure you don't have confusion with partitioned tables. Index_ID of 0 or 1 means you're only looking at the row counts for your heaps or clustered indexes.

Code Snippets

select
    t.name table_name,
    s.name schema_name,
    sum(p.rows) total_rows
from
    sys.tables t
    join sys.schemas s on (t.schema_id = s.schema_id)
    join sys.partitions p on (t.object_id = p.object_id)
where p.index_id in (0,1)
group by t.name,s.name
having sum(p.rows) = 0;

Context

StackExchange Database Administrators Q#47726, answer score: 46

Revisions (0)

No revisions yet.