DBA Scripts: Get VLF Counts

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

This script reports the virtual log file (VLF) count of every database’s transaction log, highest first, with a status band. Use it to find logs fragmented by years of small autogrowth before they slow a restore or a failover.

A high VLF count rarely raises an alert or slows a single query, so it is often overlooked. It shows up later, as crash recovery, restores and log backups that take far longer than they should.

SQL Server divides every transaction log into VLFs as it is created and grows. A few are normal. A log that grows in small steps for months or years ends up with hundreds or thousands, and everything that scans the log pays for each one.

High VLF counts slow:

  • Crash recovery and startup after an unexpected shutdown
  • Database restores
  • Transaction log backups
  • Availability Group, replication, CDC and log shipping log processing

Size is not the problem. A well-sized 500 GB log can hold few VLFs, while a poorly grown 20 GB log can hold thousands.


The Script

Run the following script against your SQL Server instance. It is read-only and needs VIEW SERVER STATE.

/*
Script Name : Get-VlfCount
Category    : monitoring
Purpose     : Virtual log file (VLF) count per database transaction log, ranked by severity.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-vlf-counts/)
Requires    : VIEW SERVER STATE
HealthCheck : Yes
Notes       : Bands: under 100 OK, 100-1000 ELEVATED, over 1000 HIGH (match the VLF collector).
              sys.dm_db_log_info on 2016 SP2+ / 2017 CU4+; DBCC LOGINFO fallback on 2012+.
*/
-- SAFE:ReadOnly
-- IMPACT:Low
SET NOCOUNT ON;

IF EXISTS (SELECT 1 FROM sys.system_objects WHERE name = 'dm_db_log_info' AND type = 'IF')
BEGIN
    -- SQL Server 2016 SP2+ / 2017 CU4+: single query
    SELECT 
        d.name AS database_name,
        d.recovery_model_desc AS recovery_model,
        COUNT(*) AS vlf_count,
        CAST(SUM(li.vlf_size_mb) AS DECIMAL(10,2)) AS log_size_mb,
        CASE 
            WHEN COUNT(*) > 1000 THEN 'HIGH'
            WHEN COUNT(*) >= 100 THEN 'ELEVATED'
            ELSE 'OK'
        END AS status
    FROM sys.databases d
    CROSS APPLY sys.dm_db_log_info(d.database_id) li
    WHERE d.state_desc = 'ONLINE'
      AND d.database_id > 4
    GROUP BY d.name, d.database_id, d.recovery_model_desc
    ORDER BY vlf_count DESC;
END
ELSE
BEGIN
    -- SQL Server 2012 – 2016 SP1 fallback: cursor + DBCC LOGINFO
    CREATE TABLE #vlf (
        database_name    sysname      NOT NULL,
        recovery_model   VARCHAR(20)  NOT NULL,
        vlf_count        INT          NOT NULL,
        log_size_mb      DECIMAL(10,2) NOT NULL,
        status           VARCHAR(10)  NOT NULL
    );

    CREATE TABLE #loginfo (
        RecoveryUnitId INT NULL,
        FileId         INT NOT NULL,
        FileSize       BIGINT NOT NULL,
        StartOffset    BIGINT NOT NULL,
        FSeqNo         BIGINT NOT NULL,
        [Status]       TINYINT NOT NULL,
        Parity         TINYINT NOT NULL,
        CreateLSN      NUMERIC(25,0) NULL
    );

    DECLARE @dbname SYSNAME;
    DECLARE @cmd    NVARCHAR(512);

    DECLARE db_cur CURSOR LOCAL FAST_FORWARD FOR
        SELECT name 
        FROM sys.databases 
        WHERE state_desc = 'ONLINE' 
          AND database_id > 4;

    OPEN db_cur;
    FETCH NEXT FROM db_cur INTO @dbname;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        TRUNCATE TABLE #loginfo;
        
        SET @cmd = N'USE ' + QUOTENAME(@dbname) + N'; DBCC LOGINFO WITH NO_INFOMSGS;';
        
        BEGIN TRY
            INSERT INTO #loginfo 
            EXEC (@cmd);

            INSERT INTO #vlf (database_name, recovery_model, vlf_count, log_size_mb, status)
            SELECT 
                @dbname,
                (SELECT recovery_model_desc 
                 FROM sys.databases 
                 WHERE name = @dbname),
                COUNT(*),
                CAST(SUM(FileSize) / 1048576.0 AS DECIMAL(10,2)),
                CASE 
                    WHEN COUNT(*) > 1000 THEN 'HIGH'
                    WHEN COUNT(*) >= 100 THEN 'ELEVATED'
                    ELSE 'OK'
                END
            FROM #loginfo;
        END TRY
        BEGIN CATCH
            -- Skip inaccessible databases
        END CATCH;

        FETCH NEXT FROM db_cur INTO @dbname;
    END

    CLOSE db_cur;
    DEALLOCATE db_cur;

    SELECT 
        database_name,
        recovery_model,
        vlf_count,
        log_size_mb,
        status
    FROM #vlf 
    ORDER BY vlf_count DESC;

    DROP TABLE #vlf;
    DROP TABLE #loginfo;
END

It returns one row per online database with its VLF count, log size and a status band. The bands (under 100 OK, 100 to 1,000 ELEVATED, over 1,000 HIGH) are rules of thumb, not hard limits: tune them to your estate.


Example Output

SSMS running Get-VlfCount on a lab instance: 33 databases ranked by VLF count, DemoDatabase first with 72 VLFs on a 2,304 MB log, every row in the OK band

One row per online database, highest VLF count first. On this lab every database is in the OK band: the worst is 72 VLFs on a 2.3 GB log, well under the 100 where the script starts to flag it. A production log that grew in small steps for years is where you see the thousands.

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-VlfCount

Add -ServerInstance SQLSERVER01 to run against another server. Script file: Get-VlfCount.sql


Understanding the Results

There is no documented Microsoft limit for VLF count, so the script applies its own bands in the status column.

database_name
recovery_model
Which database the row is for, and the recovery model its transaction log is running under. The recovery model decides how the log gets truncated, so it is the first thing to read when a count climbs straight back up after a resize.
vlf_count
Virtual log files in that database’s transaction log. The script sorts on this column, highest first, so the database that needs attention is the top row.
log_size_mb
Total log size, summed from the same VLF metadata. Read it next to the count rather than on its own: a 500 GB log holding few VLFs is healthy, a 20 GB log holding thousands is not.
status
The band the script assigns from vlf_count alone: OK under 100, ELEVATED from 100 to 1,000, HIGH above 1,000. The bands match the repo’s VLF collector job, and 100 is the line Microsoft’s own sys.dm_db_log_info example draws.

Read them as a baseline to monitor, not alarms.Act when a row reads HIGH on a server that matters: plan a log shrink and one regrow for a quiet window. ELEVATED is a note for the next sizing review, not an incident.

Very large production databases may naturally have higher counts, but thousands of VLFs should still be reviewed.


Common Causes

  • Very small autogrowth settings
  • Repeated log growth over months or years
  • Repeated cycles of shrinking and regrowing the log, which cause the worst fragmentation

How to Fix High VLF Counts

The fix is to rebuild the log once, at the right size, in a few large steps. Shrinking alone does nothing useful: the log grows straight back in small pieces.

Work Out the Size First

Size the log to its busiest normal day, plus a margin. Take the peak log space used (from sys.dm_db_log_space_usage at busy times, or your largest log backup) and add 25%.

Then grow it in 8 GB steps. Each growth over 1 GB is split into 16 VLFs, so an 8 GB step gives 16 VLFs of 512 MB, a size the log handles well. The calculation is simple:

Tip: VLFs = (log size in GB / 8) × 16. A 24 GB log grown as 8, 16, then 24 GB ends with about 50 VLFs: 48 of 512 MB, plus the few left after the shrink. The same 24 GB grown in 64 MB autogrowths would hold hundreds.

For a log under 8 GB, grow it to its final size in one step: you get 16 VLFs or fewer.

Shrink, Then Grow It Back

Do this in a quiet window. Replace the database, log file name and sizes with yours:

USE [YourDatabase];

-- 1. How big the log is and how much is in use
SELECT total_log_size_in_bytes / 1048576 AS log_size_mb,
       used_log_space_in_bytes / 1048576 AS used_mb
FROM sys.dm_db_log_space_usage;

-- 2. FULL recovery only: back the log up first so the shrink can free it
BACKUP LOG [YourDatabase] TO DISK = N'D:\Backup\YourDatabase_log.trn';

-- 3. Shrink the log as far as it will go
DBCC SHRINKFILE (YourDatabase_log, 1);

-- 4. Grow it back in 8 GB steps to the size you worked out (24 GB here)
ALTER DATABASE [YourDatabase] MODIFY FILE (NAME = YourDatabase_log, SIZE = 8192MB);
ALTER DATABASE [YourDatabase] MODIFY FILE (NAME = YourDatabase_log, SIZE = 16384MB);
ALTER DATABASE [YourDatabase] MODIFY FILE (NAME = YourDatabase_log, SIZE = 24576MB);

-- 5. A fixed growth size as the safety net, never a percentage
ALTER DATABASE [YourDatabase] MODIFY FILE (NAME = YourDatabase_log, FILEGROWTH = 1024MB);

Run the VLF script again afterwards: the count should match the calculation.

If the Shrink Does Not Free Much

The log can only shrink back to the last VLF in use. If step 3 leaves it large, take another log backup (FULL recovery) or let a checkpoint run (SIMPLE), then shrink again. If it still will not move, something is holding the log: log_reuse_wait_desc tells you what.

Do not make shrinking part of regular maintenance. Size the log once, then watch for autogrowth events: if it keeps growing, the size was wrong, not the VLFs.

Docs: Microsoft’s reference covers sys.databases and sys.dm_db_log_info in full.

Frequently Asked Questions

Does a high VLF count slow down queries?

Usually not.

High VLF counts primarily affect operations that read or process the transaction log, such as crash recovery, restores, log backups, replication, and Availability Groups.

Does shrinking the transaction log permanently fix VLF fragmentation?

No.

Shrinking may temporarily reduce the VLF count, but unless the log is regrown correctly and auto-growth settings are configured appropriately, excessive VLFs will eventually return.

What is a Virtual Log File (VLF)?

A Virtual Log File is an internal section of a SQL Server transaction log. SQL Server automatically divides log files into multiple VLFs whenever they are created or expanded.

Is a large transaction log always bad?

No.

A large transaction log that has been correctly sized can perform perfectly well. The number of VLFs is generally more important than the overall file size.

Should I monitor VLF count regularly?

Yes.

VLF count is a valuable health check that helps identify poor transaction log growth patterns before they affect recovery times and operational performance.


Related

Comments

Leave a Reply

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