Search This Blog

SQL Server Free space available in Database

This statement  will let you know what percent free space available in your selected database, this is a very useful script for those who are managing the data file size manually based on past data growth report.
SELECT AU.reserved AS Reserved_space,AU.unused as UnusedSpace,
    (AU.unallocated+AU.unused)*100/(AU.reserved+AU.unallocated) AS free_space_pct
FROM 
    (
        SELECT AU.reserved,AU.reserved-AU.used AS unused,
            CASE WHEN SF.db_size >= AU.reserved THEN (SF.db_size-AU.reserved) ELSE 0 END AS unallocated
         FROM 
                 (
                    SELECT 
                        SUM(CAST(CASE WHEN SF.status & 64 = 0 THEN SF.size ELSE 0 END AS DECIMAL(38, 2))) AS db_size
                    FROM dbo.sysfiles AS SF
                ) AS SF 
                CROSS JOIN
                        (SELECT SUM(CAST(A.total_pages AS DECIMAL(38, 2))) AS reserved,
                                SUM(CAST(A.used_pages AS DECIMAL(38, 2))) AS used
                            FROM sys.partitions AS P INNER JOIN sys.allocation_units AS A on A.container_id = P.partition_id
                        ) AS AU
    ) AS AU;