Introduction
Very often DBAs need to find the location of the physical file (MDF, LDF & NDF) of a database. Simply we can obtain the output by executing the below query. Run the script to get the SQL Server database file location for all the databases for a particular instance.
Script to find the physical file location
-- T-SQL Author: Soyeluddin Biswas -- Website: https://ourtechideas.com/ -- Created Date: 25 September 2019 -- Declare and set the server name DECLARE @ServerName NVARCHAR(128) SET @ServerName = CAST(SERVERPROPERTY('MachineName') AS NVARCHAR(128)) -- Retrieve the database file details SELECT @ServerName AS [Server Name], -- Server name d.name AS [Database Name], -- Database name d.database_id AS [Database ID], -- Database ID f.name AS [Physical File Type], -- Type of the physical file f.physical_name AS [Physical File Location], -- Location of the physical file f.state_desc AS [Online Status], -- Online status of the file f.size * 8.00 * 1024.00 AS [Size In Bytes], -- Size of the file in bytes CAST((f.size * 8.00 * 1024.00) / 1048576.00 AS NUMERIC(18,2)) AS [Size In MB], -- Size of the file in megabytes CAST((f.size * 8.00 * 1024.00) / 1073741824.00 AS NUMERIC(18,2)) AS [Size In GB], -- Size of the file in gigabytes CAST((f.size * 8.00 * 1024.00) / 1099511627776.00 AS NUMERIC(18,2)) AS [Size In TB], -- Size of the file in terabytes CAST(CAST(v.total_bytes - v.available_bytes AS FLOAT) / CAST(v.total_bytes AS FLOAT) * 100 AS NUMERIC(18,2)) AS [Used Disk Percent] -- Percentage of disk space used by the file FROM sys.master_files f INNER JOIN sys.databases d ON d.database_id = f.database_id CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.file_id) v ORDER BY d.database_id -- Sort by database ID
Result

Exploring the Query
The above query fetches crucial information related to database files. Let’s understand the key columns returned:
- Server Name: The name of the SQL Server instance on which the query is executed.
- Database Name: The name of the database.
- Database ID: The unique identifier of the database.
- Physical File Type: Specifies the type of the physical file, such as data file or log file.
- Physical File Location: The path indicating the location of the physical file.
- Online Status: Indicates whether the file is online or offline.
- Size In Bytes: The size of the file in bytes.
- Size In MB: The size of the file in megabytes.
- Size In GB: The size of the file in gigabytes.
- Size In TB: The size of the file in terabytes.
- Used Disk Percent: The percentage of disk space used by the file.