Friday, January 3, 2020

Get current database files information

 Understanding SQL Server Database Files and Filegroups

When working with SQL Server, it's crucial to understand how database files and filegroups are structured. This knowledge helps you manage your database's storage efficiently and optimize performance. Below is a useful SQL query that provides detailed information about your database files, including their size, available space, and growth settings.


SELECT f.name AS [File Name]
 ,f.physical_name AS [Physical Name]
 ,CAST((f.size / 128.0) AS DECIMAL(15, 2)) AS [Total Size in MB]
 ,CAST(f.size / 128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS INT) / 128.0 AS DECIMAL(15, 2)) AS [Available Space In MB]
 ,f.[file_id]
 ,fg.name AS [Filegroup Name]
 ,f.is_percent_growth
 ,f.growth
 ,fg.is_default
 ,fg.is_read_only
 ,fg.is_autogrow_all_files
FROM sys.database_files AS f WITH (NOLOCK)
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK) ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id]
OPTION (RECOMPILE);
  

This query gives you a comprehensive overview of your database's physical files. You can see their **logical names**, **physical paths**, **total allocated size in MB**, and the **remaining free space**. It also displays details about the **filegroups** they belong to, such as their **growth settings** and whether they are **read-only** or **autogrow all files**.

For more in-depth information, you can refer to the official Microsoft documentation on filegroups and the sys.database_files system catalog view.

Popular Posts