DBA Scripts: Get Database Sizes and Free Space

🔧Part of the DBA-Tools Project, copy/paste SQL Server scripts and health checks.In: Storage & Capacity

Database size checks are one of the first things I review when assessing a SQL Server environment. The goal is simple: see where storage is being consumed, spot the databases that need attention, and confirm there is room for normal growth.

The risk is not growth itself. The risk is unexpected growth, insufficient free space, or discovering too late that the SQL Server host cannot support the next expansion.

This script lists every online user database with its allocated data and log sizes, current usage and free space, biggest database first.

Review it with Disk Space beside it: a database can have room inside its files while the drive underneath cannot take the next growth. For a triage view ordered by tightest free space first, see Database Free Space Summary.


When to Run This Script

  • When investigating unexpected database or transaction log growth.
  • During storage investigations, with the disk space check beside it.
  • Before a migration or an application change that will add data volume.
  • As part of a routine SQL Server health check.

The Script

Run the following script against your SQL Server instance. It is read-only and needs VIEW ANY DATABASE, plus access to each online database, because it opens every one.

/*
Script Name : Get-DatabaseSizesAndFreeSpace
Category    : storage-capacity-management
Purpose     : Data and log file sizes with used and free space for all online user databases.
              FILEPROPERTY runs inside each database, through dynamic SQL.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-database-sizes-and-free-space/)
Requires    : VIEW ANY DATABASE, plus access to each online database it inspects (it opens every database)
HealthCheck : Yes
*/
-- SAFE:ReadOnly
-- IMPACT:Low
SET NOCOUNT ON;

CREATE TABLE #sizes (
    database_name sysname NOT NULL,
    data_size_mb DECIMAL(18,1) NOT NULL,
    data_used_mb DECIMAL(18,1) NOT NULL,
    log_size_mb DECIMAL(18,1) NOT NULL,
    log_used_mb DECIMAL(18,1) NOT NULL
);

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'
USE ' + QUOTENAME(name) + N';
INSERT INTO #sizes (database_name, data_size_mb, data_used_mb, log_size_mb, log_used_mb)
SELECT
    DB_NAME(),
    CAST(ROUND(SUM(CASE WHEN type = 0 THEN size * 8.0 / 1024 ELSE 0 END), 1) AS DECIMAL(18,1)),
    CAST(ROUND(SUM(CASE WHEN type = 0
        THEN ISNULL(FILEPROPERTY(name, ''SpaceUsed''), size) * 8.0 / 1024
        ELSE 0 END), 1) AS DECIMAL(18,1)),
    CAST(ROUND(SUM(CASE WHEN type = 1 THEN size * 8.0 / 1024 ELSE 0 END), 1) AS DECIMAL(18,1)),
    CAST(ROUND(SUM(CASE WHEN type = 1
        THEN ISNULL(FILEPROPERTY(name, ''SpaceUsed''), size) * 8.0 / 1024
        ELSE 0 END), 1) AS DECIMAL(18,1))
FROM sys.database_files;
'
FROM sys.databases
WHERE state_desc = 'ONLINE'
  AND database_id > 4;

IF LEN(@sql) > 0
    EXEC sys.sp_executesql @sql;

SELECT
    database_name,
    data_size_mb,
    CAST(ROUND(data_size_mb - data_used_mb, 1) AS DECIMAL(18,1)) AS data_free_mb,
    CAST(ROUND(CASE WHEN data_size_mb > 0
        THEN 100.0 * (data_size_mb - data_used_mb) / data_size_mb
        ELSE NULL END, 1) AS DECIMAL(5,1)) AS data_free_pct,
    log_size_mb,
    CAST(ROUND(log_size_mb - log_used_mb, 1) AS DECIMAL(18,1)) AS log_free_mb,
    CAST(ROUND(CASE WHEN log_size_mb > 0
        THEN 100.0 * (log_size_mb - log_used_mb) / log_size_mb
        ELSE NULL END, 1) AS DECIMAL(5,1)) AS log_free_pct
FROM #sizes
ORDER BY data_size_mb + log_size_mb DESC;

DROP TABLE #sizes;
Get-DatabaseSizesAndFreeSpace results in SSMS, 30 online user databases largest first: DemoDatabase with 2048 MB of data 99.5 percent free and a 2304 MB log 19.9 percent free, then five migdb databases at 790 MB with only 0.5 percent data free

Largest database first, so the row that matters is rarely the top one. DemoDatabase leads on size, with a mostly empty data file.

The rows this script is for sit right under it: five migdb_ databases at 790 MB each with 0.5% data free, where the next insert that does not fit triggers an autogrowth.

The two read-only Lab1004_snap_Sales copies show 0.0 log free, and that is not a full log. FILEPROPERTY returns NULL for the log of a read-only database, and the script counts a NULL as fully used.

Run it from the DBA Tools repo
git clone https://github.com/peterwhyte-lgtm/dba-tools
cd dba-tools
.\Initialize-Environment.ps1
.\run.ps1 Get-DatabaseSizesAndFreeSpace

Add -ServerInstance SQLSERVER01 to run against another server. Script files: Get-DatabaseSizesAndFreeSpace.sql · Get-DatabaseSizesAndFreeSpace.ps1


Understanding the Results

No fixed threshold fits every environment. A large database with little free space can be normal if growth is controlled and the storage is there. What the columns give you is the shape of each database, and the rows that stand out.

database_name
Online user databases only. System databases are never listed. Act when a database you expected is missing. It is offline, mid-restore, or you cannot open it: a permissions gap shows as a missing row, not an error.
data_size_mb
Space the data files are allocated on disk, not how much is in use. This is the figure to reconcile against free disk.
data_free_mb
data_free_pct
Unused space inside the data files, which SQL Server can fill without asking the operating system for anything. Act when it is in low single digits. The next insert that does not fit triggers an autogrowth, so check the growth increment and the volume before it fires.
log_size_mb
Allocated transaction log size. Large is not wrong if it was sized for the busiest job of the month; look for a size nobody chose.
log_free_mb
log_free_pct
Unused space inside the log. A large, nearly empty log grew once under something and was never sized back; a nearly full one is the urgent case. Act when it is low and falling. Check log_reuse_wait_desc in sys.databases: every value it can return, and what to do about each.

Free Space That Nobody Chose

Large amounts of unused space are worth a question rather than an alarm. Old growth, an archive that ran, a restore from a bigger environment and deliberate pre-sizing all look identical in these columns. The question is whether the current size is one somebody chose.

Docs: Microsoft’s reference covers sys.master_files, sys.database_files and sys.databases in full.

Frequently Asked Questions

Should I shrink databases with free space?

Usually not.

If the space is expected to be reused, keeping the allocation is normally preferable. Shrinking files can introduce fragmentation and often results in the files growing again.

Why check database free space and disk space separately?

Database free space shows what is available inside the SQL Server files. Disk space shows whether the server can support the next growth. You need both for capacity management.

How much free space should a database keep?

Enough for the growth you expect, so autogrowth stays rare. Compare free space with the recent growth rate rather than using a fixed percentage.

What permissions does it need?

It is read-only and needs VIEW ANY DATABASE plus access to each online database, because it opens every one.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *