SQL Server: Get the Current Size and Free Space of Data File and Log File



I recently discovered our application monitoring tool only looks at the total size of the data and log file.  In our case we had excessive database growth but the monitoring tool only knew how much the data file grew, not how much space the runaway process used up inside of the data file before the data file was forced to expand.

Below is a simple query which will allow you to get the current size of the data and log files along with the space still available.

 USE <YOUR DATABASE>

SELECT DB_NAME() AS Database_Name,
NAME FileName,
SIZE/128.0 Current_Size_MB,
SIZE/128.0 - FILEPROPERTY(NAME, 'SPACEUSED')/128.0 Free_Space_MB,
GETDATE() DateTime
FROM SYS.DATABASE_FILES;


First, use the function DB_NAME() with no parameter to get the name of the current database. Next, you will need the NAME and SIZE of the files from DMV SYS.DATABASE_FILES.

Name is the name of the file.

Size is the number of 8KB pages in the file.  Since a MB is 1024 KB, you divide the number of 8KB files by 1024/8 = 128 to get the size of the file in MB.

Use the FILEPROPERTY() function with the  name of the file and the file property 'SPACEUSED' to get the actual space used in the file. It is also returns a count of 8KB pages so divide by 128.0.

Next, subtract the SPACEUSED from the SIZE to get the available free space.

Finally, use the GETDATE() function for the date and time you collected the data.

Quick note, using 128.0 instead of 128 will implicitly cast the result as a float which will return a more precise calculation.  Do not use 128.0 if you are only interested in integer results but be aware you will be losing information.

Popular posts from this blog

Power BI Report Server: "An Error Has Occurred" or Power BI Report Server: "My Power BI Report is Coming up Blank" or Power BI Report Server: "401 and 403” Errors From Nowhere

SQL SERVER 2017: STRING_AGG

Dynamic Label Positions With SSRS