How to clear msdb backup history in SQL Server

SQL-Server

After a while, the msdb database can be overloaded with backup history, and clearing that history can be a pain. You can use the T-SQL code below to clear the msdb backup history in incremental steps of 1 week.

use msdb
go
declare @retentionDate datetime = DATEADD(MONTH, -3, getdate())
declare @oldest_date datetime = (select min(backup_start_date) from msdb.dbo.backupset)
while (@oldest_date  < @retentionDate)
begin
    print 'sp_delete_backuphistory ' + CAST(@oldest_date AS varchar)
    exec msdb.dbo.sp_delete_backuphistory @oldest_date
    --  Delete by 1 week increments
    set @oldest_date = DATEADD(WEEK, 1, @oldest_date)
    checkpoint
end
exec msdb.dbo.sp_delete_backuphistory @retentionDate
go