TSQL – How to get sizes of all databases on a server

Typical database in SQL Server is a combination of Data Files and Log Files. Here is the query to find size of Data files, Log Files, and Total Size of Database in GB

SELECT [Database Name] = DB_NAME(database_id),
       [Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
                     WHEN Type_Desc = 'LOG'  THEN 'Log File(s)'
                     ELSE 'Total' END,
       [Size in GB] = CAST( ((SUM(Size)* 8) / 1024.0) AS DECIMAL(18,2) )
FROM   sys.master_files
                     (DB_NAME(database_id), Type_Desc),
ORDER BY      DB_NAME(database_id), Type_Desc DESC
-- NOTE: GROUPING SETS is not available in SQL 2005 or older versions, you have to GROUP BY usign DB_NAME(database_id), Type_Desc

There are plenty of other ways to get the Database size including lot of other information, few of them are listed below:

-- This gives total Database size of all databases on the SQL instance
-- sp_helptext also gives Created Date, Owner, Status and Compatibility Level

sp_helpdb 'msdb' -- msdb is the DB Name in the example
-- In addition to Database size, it gives Location and Size of each Data Files and Log Files including its growth options

use msdb
-- It is used to find unallocated space

-- If you like playing around different tables, go ahead and experiment wtih following tables
select * from sys.database_files
select * from sys.master_files
select * from sys.allocation_units 
select * from sys.partitions 
select * from sys.data_spaces
This entry was posted in Productivity, Script, SQL and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s