Microsoft SQL Server logo

Easily querying all the database and log file sizes on SQL Server

Reading Time: 2 minutes.

Quite often you get the need to simply quickly query all the database sizes on MS SQL Server – most typically, for us, this need arises when a development machine gets low on disk space, and we need to check if some database’s log size has been growing, or if something else is wrong.

In my daily work, I rarely encounter this requirement anymore. Azure has almost entirely obliterated the need for such diagnostics, since it’s so easy to spin up or scale up new development resources when need be.

Solution

Table of Contents

The script below will query all database sizes and return them in a neat table. Nice and easy!

WITH fs
AS
(
    SELECT database_id, TYPE, SIZE * 8.0 / 1024 SIZE
    FROM sys.master_files
)
SELECT 
    name,
    (SELECT SUM(SIZE) FROM fs WHERE TYPE = 0 AND fs.database_id = db.database_id) DataFileSizeMB,
    (SELECT SUM(SIZE) FROM fs WHERE TYPE = 1 AND fs.database_id = db.database_id) LogFileSizeMB
FROM sys.databases db

Postface

This post is kind of a classic – it was one of the first things I documented on my blog on 2014. But since it’s almost a one-liner, I felt silly about publishing it – and whenever I might’ve needed the SQL commands, I’ve just been accessing it from the admin interface ever since.

That’s cumbersome, though, so I finally thought it’s worthwhile to publish it after all.

mm

6
Leave a Reply

avatar
5000
3 Comment threads
3 Thread replies
5 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
Raj Kamal SinghCathyMrBmmFred Recent comment authors
  Subscribe  
Notify of
Fred
Guest
Fred

Hey Anti, Thanks for the script!

I’ve tried your script and all I get are NULL. Why is that ?

MrB
Guest
MrB

I’m guessing it’s because you aren’t getting values back from sys.master_files

Cathy
Guest
Cathy

Your script was very helpful. Thanks Antti!

Raj Kamal Singh
Guest
Raj Kamal Singh

WITH fs
AS
(
SELECT db_name(database_id) AS DatabaseName
,type_desc AS TypeDesc,
Physical_Name AS Location,
(size * 8) /1024 AS SizeInMB,
(size * 8) /1024/1024 AS SizeInGB
FROM sys.master_files
)
SELECT name,
(SELECT SUM(SizeInMB) FROM fs WHERE TypeDesc = ‘ROWS’ AND fs.DatabaseName = db.name) DataFileSizeMB,
(SELECT SUM(SizeInGB) FROM fs WHERE TypeDesc = ‘ROWS’ AND fs.DatabaseName = db.name) DataFileSizeGB,
(SELECT SUM(SizeInMB) FROM fs WHERE TypeDesc = ‘Log’ AND fs.DatabaseName = db.name) LogFileSizeMB,
(SELECT SUM(SizeInGB) FROM fs WHERE TypeDesc = ‘Log’ AND fs.DatabaseName = db.name) LogFileSizeGB
FROM sys.databases db