Home / Guides / Check SQL Server backup history on many instances

Check SQL Server backup history across instances

"When was this database last backed up?" sounds like a one-line question until you have twenty instances and a few hundred databases. This guide shows where SQL Server records its backups, a query that lists the newest full, differential and log backup of every database (including the ones that have none), a PowerShell script that checks many instances at once, what the history cannot tell you, and where these methods stop. We ran every query and script on SQL Server 2025 and 2022 test instances.

Short answer.

Every successful backup is a row in msdb.dbo.backupset: type is D for full, I for differential and L for log, with backup_finish_date, size and copy-only flag; the file names are in msdb.dbo.backupmediafamily. Start from sys.databases and look up the newest row of each type, so databases with no backup at all show up too. For many instances, run that query in a PowerShell loop with Invoke-Sqlcmd, or use dbatools' Get-DbaLastBackup.

Two things the history never shows: a backup that failed (it leaves no row; look for error 3041 in the error log) and a backup taken on another server, such as another replica of an availability group.

Where SQL Server records backups

SQL Server writes the history of backups and restores into the msdb database of the instance that ran them. The tables that matter:

  • backupset: one row per successful backup. database_name, type (D full, I differential, L log, plus F, G, P, Q for file, partial and their differentials), backup_start_date and backup_finish_date in the server's local time, backup_size, compressed_backup_size, is_copy_only, has_backup_checksums, is_damaged and recovery_model.
  • backupmediafamily: the file, URL or device each backup was written to (physical_device_name), joined on media_set_id. A backup striped over several files has one row per file.
  • restorehistory: one row per restore, with the target database and the backup_set_id it came from.

A third-party tool that backs up through SQL Server's own backup interface (a virtual device, for example) is normally recorded here as well; a tool that copies the database files some other way is not.

The newest backup of every database on one instance

Querying backupset alone only finds databases that have a backup. Start from sys.databases instead, so a database that was never backed up appears with NULL dates, at the top of the list:

USE [msdb];
-- The newest full, differential and log backup of every database on this instance, never-backed-up first
SELECT  d.name                AS database_name,
        d.recovery_model_desc AS recovery_model,
        d.state_desc          AS state,
        b.last_full,
        b.last_diff,
        b.last_log,
        DATEDIFF(HOUR,   b.last_full, GETDATE()) AS hours_since_full,
        DATEDIFF(MINUTE, b.last_log,  GETDATE()) AS minutes_since_log
FROM sys.databases AS d
OUTER APPLY (
    SELECT MAX(CASE WHEN bs.type = 'D' THEN bs.backup_finish_date END) AS last_full,   -- copy-only fulls included
           MAX(CASE WHEN bs.type = 'I' THEN bs.backup_finish_date END) AS last_diff,
           MAX(CASE WHEN bs.type = 'L' THEN bs.backup_finish_date END) AS last_log
    FROM dbo.backupset AS bs
    WHERE bs.database_name = d.name
) AS b
WHERE d.name <> N'tempdb'
  AND d.source_database_id IS NULL                 -- leave out database snapshots
ORDER BY CASE WHEN b.last_full IS NULL THEN 0 ELSE 1 END, b.last_full, d.name;
  • Copy-only full backups count as full here, because they can be restored. Availability group secondaries before SQL Server 2025 can only take copy-only full backups. If you want to see them apart, add bs.is_copy_only to the filter.
  • Log backups only matter for databases in FULL or BULK_LOGGED recovery. A database in SIMPLE recovery always shows NULL for last_log, and that is fine.
  • Matching is by name. If a database was dropped and recreated with the same name, its old backups still match. Database snapshots are left out, and so is tempdb, which cannot be backed up.

Every backup of the last week, with size and file

When you need the detail, such as how long the full backups take or where the log backups went:

USE [msdb];
-- Every backup in the last 7 days, newest first, with size, duration and file
SELECT  bs.database_name,
        CASE bs.type WHEN 'D' THEN 'Full' WHEN 'I' THEN 'Differential' WHEN 'L' THEN 'Log'
                     WHEN 'F' THEN 'File/filegroup' WHEN 'G' THEN 'Differential file'
                     WHEN 'P' THEN 'Partial' WHEN 'Q' THEN 'Differential partial' END AS backup_type,
        bs.is_copy_only,
        bs.backup_start_date,
        bs.backup_finish_date,
        DATEDIFF(SECOND, bs.backup_start_date, bs.backup_finish_date) AS seconds,
        CAST(bs.backup_size / 1048576.0 AS decimal(12, 1))            AS size_mb,
        CAST(bs.compressed_backup_size / 1048576.0 AS decimal(12, 1)) AS compressed_mb,
        bs.has_backup_checksums,
        bs.is_damaged,
        bs.user_name,
        mf.physical_device_name
FROM dbo.backupset AS bs
LEFT JOIN dbo.backupmediafamily AS mf ON mf.media_set_id = bs.media_set_id
WHERE bs.backup_start_date >= DATEADD(DAY, -7, GETDATE())
ORDER BY bs.backup_finish_date DESC, mf.family_sequence_number;

is_damaged = 1 means the backup was taken with CONTINUE_AFTER_ERROR despite errors: do not rely on it. has_backup_checksums = 0 means the backup was taken without WITH CHECKSUM.

Restores, too

restorehistory answers "who restored what over this database?" and "has anyone ever test-restored this backup?":

USE [msdb];
-- Restores in the last 30 days: which database, from which backup, by whom
SELECT  rh.restore_date,
        rh.destination_database_name,
        CASE rh.restore_type WHEN 'D' THEN 'Database' WHEN 'I' THEN 'Differential' WHEN 'L' THEN 'Log'
                             WHEN 'F' THEN 'File' WHEN 'G' THEN 'Filegroup' WHEN 'V' THEN 'Verify only' END AS restore_type,
        rh.[replace],
        rh.user_name,
        bs.database_name      AS source_database,
        bs.server_name        AS source_server,
        bs.backup_finish_date AS backup_taken
FROM dbo.restorehistory AS rh
LEFT JOIN dbo.backupset AS bs ON bs.backup_set_id = rh.backup_set_id
WHERE rh.restore_date >= DATEADD(DAY, -30, GETDATE())
ORDER BY rh.restore_date DESC;

The permissions it needs

Less than you might expect. On both our SQL Server 2025 and 2022 instances, public in msdb has SELECT on backupset, backupmediafamily and restorehistory, and the guest user in msdb is enabled. A test login with no user in msdb and no other rights could run every query in this guide. sys.databases lists every database for logins with VIEW ANY DATABASE, which public has by default. If your servers have been hardened and those grants were removed, grant SELECT on the three tables to your monitoring login.

Check many instances at once

PowerShell: loop with Invoke-Sqlcmd

This script runs the "newest backup" query on every instance in a list with Invoke-Sqlcmd from Microsoft's SqlServer module (Install-Module SqlServer once). It flags each database whose newest full backup is too old, that has had no full or differential backup for too long, or (in FULL or BULK_LOGGED recovery) whose newest log backup is too old, writes a CSV, and reports the instances it could not reach at the end instead of stopping. Ages are measured against each server's own clock.

param(
    [string[]]$ServerInstance = @('SQL01', 'SQL02', 'SQL03\SALES'),
    [int]$FullDays            = 8,      # newest full backup older than this: flagged
    [int]$DataHours           = 26,     # newest full OR differential older than this: flagged
    [int]$LogMinutes          = 60,     # FULL / BULK_LOGGED databases: newest log backup older than this: flagged
    [switch]$All,                       # list every database, not only the flagged ones
    [switch]$TrustServerCertificate,    # only for servers without a trusted certificate
    [string]$CsvPath          = "$env:USERPROFILE\Desktop\BackupStatus.csv"
)
Import-Module SqlServer -ErrorAction Stop

$query = @"
SET NOCOUNT ON;
SELECT  d.name AS database_name, d.recovery_model_desc AS recovery_model, d.state_desc AS state,
        b.last_full, b.last_diff, b.last_log, GETDATE() AS server_now
FROM sys.databases AS d
OUTER APPLY (
    SELECT MAX(CASE WHEN bs.type = 'D' THEN bs.backup_finish_date END) AS last_full,
           MAX(CASE WHEN bs.type = 'I' THEN bs.backup_finish_date END) AS last_diff,
           MAX(CASE WHEN bs.type = 'L' THEN bs.backup_finish_date END) AS last_log
    FROM msdb.dbo.backupset AS bs
    WHERE bs.database_name = d.name
) AS b
WHERE d.name <> N'tempdb' AND d.source_database_id IS NULL;
"@

function Get-Date2($v) { if ($v -is [DBNull] -or $null -eq $v) { $null } else { [datetime]$v } }

$found  = [System.Collections.Generic.List[object]]::new()
$failed = [System.Collections.Generic.List[object]]::new()

$sqlArgs = @{ Database = 'master'; Query = $query; QueryTimeout = 120; ErrorAction = 'Stop' }
if ($TrustServerCertificate) { $sqlArgs.TrustServerCertificate = $true }

foreach ($instance in $ServerInstance) {
    try {
        $rows = Invoke-Sqlcmd -ServerInstance $instance @sqlArgs
    }
    catch {
        $failed.Add([pscustomobject]@{ Instance = $instance; Error = $_.Exception.Message })
        continue
    }
    foreach ($r in $rows) {
        $now  = [datetime]$r.server_now           # the server's clock, so no time zone mix-ups
        $full = Get-Date2 $r.last_full
        $diff = Get-Date2 $r.last_diff
        $log  = Get-Date2 $r.last_log
        $data = @($full, $diff) | Where-Object { $_ } | Sort-Object -Descending | Select-Object -First 1

        $problems = @()
        if ($r.state -ne 'ONLINE') { $problems += "state $($r.state)" }
        elseif (-not $full) { $problems += 'no full backup recorded' }
        else {
            if ($full -lt $now.AddDays(-$FullDays))    { $problems += "full older than $FullDays days" }
            if ($data -lt $now.AddHours(-$DataHours))  { $problems += "no full or differential in $DataHours hours" }
            if ($r.recovery_model -ne 'SIMPLE' -and $r.database_name -ne 'model') {
                if (-not $log) { $problems += 'no log backup recorded' }
                elseif ($log -lt $now.AddMinutes(-$LogMinutes)) { $problems += "log older than $LogMinutes minutes" }
            }
        }
        if ($All -or $problems) {
            $found.Add([pscustomobject]@{
                Instance  = $instance
                Database  = $r.database_name
                Recovery  = $r.recovery_model
                LastFull  = $full
                LastDiff  = $diff
                LastLog   = $log
                Problem   = $problems -join '; '
            })
        }
    }
}

$sorted = $found | Sort-Object Instance, Database
$sorted | Format-Table Instance, Database, Recovery, LastFull, LastDiff, LastLog, Problem -AutoSize
$sorted | Export-Csv -Path $CsvPath -NoTypeInformation -Encoding UTF8
"{0} databases listed from {1} instances, written to {2}" -f $found.Count, ($ServerInstance.Count - $failed.Count), $CsvPath

foreach ($f in $failed) { Write-Warning "$($f.Instance): $($f.Error)" }

Save it as C:\Scripts\Get-BackupStatus.ps1 and run it with your own instance names and limits:

C:\Scripts\Get-BackupStatus.ps1 -ServerInstance SQL01, SQL02, 'SQL03\SALES'

# The instance list from a file (one per line), daily fulls, log backups every 15 minutes, every database listed:
C:\Scripts\Get-BackupStatus.ps1 -ServerInstance (Get-Content C:\Scripts\instances.txt) -FullDays 1 -DataHours 26 -LogMinutes 30 -All
  • -FullDays, -DataHours, -LogMinutes: your backup schedule plus some slack. The defaults suit a weekly full, a daily differential and log backups at least hourly.
  • -All: list every database, not only the flagged ones.
  • -TrustServerCertificate: version 22 of the SqlServer module encrypts the connection and checks the server's certificate. Against our test server with a self-signed certificate, the script stopped with "The certificate chain was issued by an authority that is not trusted" until we added this switch. The real fix is a trusted certificate; the switch skips the check and is only reasonable on a network you trust.

The model database is in FULL recovery by default but is rarely log-backed-up, so the script does not ask for its log backups. An offline or restoring database is listed with its state instead of its backup age.

dbatools: Get-DbaLastBackup

The free, community-run dbatools module does the same per database, across several instances, including databases with no backup. Its Status column says things like "No Log Back Up in the last hour". Get-DbaDbBackupHistory returns the individual backups.

# Install-Module dbatools -Scope CurrentUser    (once)
Get-DbaLastBackup -SqlInstance SQL01, SQL02, 'SQL03\SALES' |
    Select-Object SqlInstance, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, Status |
    Export-Csv "$env:USERPROFILE\Desktop\LastBackups.csv" -NoTypeInformation -Encoding UTF8

# Every backup of one database in the last 7 days
Get-DbaDbBackupHistory -SqlInstance SQL01 -Database Sales -Since (Get-Date).AddDays(-7) |
    Select-Object Database, Type, Start, End, TotalSize, Path, IsCopyOnly

Tested on Windows 11 with SQL Server 2025 Developer (17.0.5045.3) and SQL Server 2022 Express (16.0.1220.3): we took full, differential, log and copy-only backups, made one fail on purpose, restored a copy and created a database snapshot, then ran all three queries, the permissions above with a test login, the PowerShell script (SqlServer module 22.4.5.1, two instances and an unreachable name, an offline database) and dbatools 2.9.1. In our test Get-DbaLastBackup also listed the database snapshot as never backed up.

What the backup history does not tell you

  • Failed backups. backupset holds successful backups only. When we pointed a backup at a path that does not exist, no row was written. The failure is in the SQL Server error log as error 3041, "BACKUP failed to complete the command BACKUP DATABASE ...", and in the Windows Application log as event ID 3041 from source MSSQLSERVER (or MSSQL$InstanceName). See reading the error logs of many instances and failed SQL Agent jobs, since most backups run as jobs.
  • Backups taken on another server. msdb is local to each instance and is not part of any availability group. If your backups run on a secondary replica, the primary's history shows nothing for those databases. Query every replica and take the newest backup per database.
  • Whether the file still exists or restores. The row says a backup was written, not that the file is still on the share or that it restores. Only a restore proves that; restorehistory shows whether anyone has tried.

How long SQL Server keeps backup history

Unlike SQL Agent job history, backup history has no built-in limit: it grows until something deletes it. Microsoft recommends running sp_delete_backuphistory regularly, and the maintenance plan History Cleanup Task calls it for you. It removes the history rows (backups and restores) older than a date; the backup files themselves are not touched:

USE [msdb];
-- Keep 90 days of backup and restore history (the backup files are not touched)
DECLARE @Oldest datetime = DATEADD(DAY, -90, GETDATE());
EXECUTE dbo.sp_delete_backuphistory @oldest_date = @Oldest;

Whatever the cleanup keeps is all you can look back on. If an auditor asks when a database was last restored eight months ago, and the cleanup keeps 90 days, the answer is gone.

Where these methods stop

  • A check, not a record. Each run reads the servers again. Once the history cleanup removes a row, it is gone unless you kept the CSV.
  • The backups are in one place, the failures in another. Why a backup is missing is usually in the error log, the job history or the Windows Event Log, which are separate queries.
  • Availability groups need the whole group. You have to know which replicas to ask and combine the answers yourself.
  • Someone has to run it. A scheduled task can run the script and email the CSV, but that is another piece of plumbing to maintain.

Questions

Where is SQL Server backup history stored?

In the msdb database of the instance that ran the backup: msdb.dbo.backupset has one row per successful backup (type D full, I differential, L log), msdb.dbo.backupmediafamily has the file or device it was written to, and msdb.dbo.restorehistory has the restores.

How do I find databases that have never been backed up?

Start from sys.databases and look up the newest backupset row for each database with OUTER APPLY or a LEFT JOIN. Databases with no row come back with NULL dates. A query on backupset alone cannot find them, because it only contains databases that were backed up.

Does msdb show failed backups?

No. backupset only records successful backups, so a failed backup leaves no row. The failure is in the SQL Server error log as error 3041 ("BACKUP failed to complete the command") and in the Windows Application log as event ID 3041 from the SQL Server instance's source.

Why does a database in an availability group look like it was never backed up?

Backup history is kept in msdb on the instance that took the backup, and msdb is not part of the availability group. If the backups run on a secondary replica, only that replica's history shows them. Query every replica and take the newest backup per database.

How long does SQL Server keep backup history?

Until something deletes it: there is no built-in limit. sp_delete_backuphistory, or the History Cleanup Task in a maintenance plan, removes backup and restore history older than a date you choose; the backup files are not touched. To keep it longer without growing msdb, copy it elsewhere before the cleanup runs, for example with a collector such as LogTrawler.

Related

Sources (Microsoft Learn): backupset, backupmediafamily, restorehistory, sp_delete_backuphistory, History Cleanup Task, Database Engine errors 3000 to 3999 (3041), Backups on secondary replicas, Copy-only backups, Invoke-Sqlcmd. dbatools: Get-DbaLastBackup, Get-DbaDbBackupHistory.

An unhandled error has occurred. 🗙