How to Reduce the Size of Your Local SQL Databases on a Schedule

> 5 minutes could save you 14% or more on disk space and car insurance
Cover Image for How to Reduce the Size of Your Local SQL Databases on a Schedule

Overview

Sometimes tough choices have to be made regarding disk space when running multiple Sitecore implementations on one enterprise development machine. In this post, we will demonstrate how to reduce the size of your Sitecore databases on-demand and on-schedule.

Before You Start: How Big Are Your DBs?

For fun, run this command to see how big all your databases are before you run the reduction scripts:


_3
SELECT
_3
CAST(SUM(size) * 8.0 / 1024 / 1024 AS DECIMAL(18,2)) AS TotalSizeGB
_3
FROM sys.master_files;

I reduced my total database sizes by 14%.

Step 1: Reclaim Disk Space On-Demand

When databases are restored via BACPAC or BAK files, there is some post-restore maintenance that can be done to reclaim disk space.

SQL Statements This sets the recovery model to simple, which will reduce the size of your transaction log.


_1
ALTER DATABASE {your_database_name_here} SET RECOVERY SIMPLE;

To run this on all of your user databases, run the following script:


_27
_27
DECLARE @databaseName nvarchar(max);
_27
DECLARE @sql nvarchar(max);
_27
DECLARE database_cursor CURSOR FOR
_27
SELECT
_27
d.[name],
_27
'ALTER DATABASE [' + d.[name] + '] SET RECOVERY SIMPLE;' AS [Query]
_27
FROM
_27
[sys].[databases] AS d
_27
WHERE
_27
d.[database_id] > 4
_27
AND
_27
d.[recovery_model_desc] != 'SIMPLE'
_27
ORDER BY
_27
d.[name]
_27
OPEN database_cursor
_27
FETCH NEXT FROM database_cursor
_27
INTO @databaseName, @sql
_27
WHILE @@FETCH_STATUS = 0
_27
BEGIN
_27
PRINT 'Altering database ' + @databaseName;
_27
EXEC(@sql)
_27
FETCH NEXT FROM database_cursor
_27
INTO @databaseName, @sql
_27
END
_27
CLOSE database_cursor;
_27
DEALLOCATE database_cursor;

This shrinks the transaction log file, which you will want to do after changing the recovery model.


_4
--Get the name of the log file(s)
_4
SELECT [file_id], [name] FROM [sys].[database_files] WHERE [type_desc] = 'LOG';
_4
--Shrink the log file.
_4
DBCC SHRINKFILE (N'{copy_log_file_name_here}' , 0, TRUNCATEONLY);

To run this on all of your user databases, run the following script:


_28
DECLARE @databaseName nvarchar(max);
_28
DECLARE @databaseFileName nvarchar(max);
_28
DECLARE @sql nvarchar(max);
_28
DECLARE database_cursor CURSOR FOR
_28
SELECT
_28
d.[name],
_28
mf.[name],
_28
'USE [' + d.[name] + ']; DBCC SHRINKFILE(N''' + mf.[name] + ''', 0, TRUNCATEONLY);' AS [Query]
_28
FROM
_28
[sys].[master_files] AS mf
_28
INNER JOIN [sys].[databases] AS d ON
_28
mf.[database_id] = d.[database_id]
_28
WHERE
_28
d.[database_id] > 4
_28
ORDER BY
_28
d.[name]
_28
OPEN database_cursor
_28
FETCH NEXT FROM database_cursor
_28
INTO @databaseName, @databaseFileName, @sql
_28
WHILE @@FETCH_STATUS = 0
_28
BEGIN
_28
PRINT 'Shrinking database file ' + @databaseFileName + ' of database ' + @databaseName;
_28
EXEC(@sql)
_28
FETCH NEXT FROM database_cursor
_28
INTO @databaseName, @databaseFileName, @sql
_28
END
_28
CLOSE database_cursor;
_28
DEALLOCATE database_cursor;

Step 2: Set Up a Schedule

We are going to use SQL Server Agent jobs to run the queries above.

2.1: Configure the SQL Server Agent Service

Change the Startup Type to Automatic (Delayed Start) before you start it, as the default Startup Type is Disabled.

SQL Server Agent Service Configuration Screenshot

2.2: Create the SQL Server Agent Job

Execute the following SQL script to create the SQL Server Agent job:


_146
USE [msdb]
_146
GO
_146
_146
/****** Object: Job [Reduce Database Sizes] Script Date: 8/6/2025 12:25:07 PM ******/
_146
BEGIN TRANSACTION
_146
_146
DECLARE @ownerLoginName NVARCHAR(128);
_146
-- Get the current user's login name
_146
SET @ownerLoginName = SUSER_SNAME();
_146
_146
DECLARE @ReturnCode INT
_146
SELECT @ReturnCode = 0
_146
/****** Object: JobCategory [Database Maintenance] Script Date: 8/6/2025 12:25:07 PM ******/
_146
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'Database Maintenance' AND category_class=1)
_146
BEGIN
_146
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'Database Maintenance'
_146
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
_146
_146
END
_146
_146
DECLARE @jobId BINARY(16)
_146
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Reduce Database Sizes',
_146
@enabled=1,
_146
@notify_level_eventlog=0,
_146
@notify_level_email=0,
_146
@notify_level_netsend=0,
_146
@notify_level_page=0,
_146
@delete_level=0,
_146
@description=N'No description available.',
_146
@category_name=N'Database Maintenance',
_146
@owner_login_name=@ownerLoginName, @job_id = @jobId OUTPUT
_146
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
_146
/****** Object: Step [Update to Simple Recovery] Script Date: 8/6/2025 12:25:07 PM ******/
_146
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Update to Simple Recovery',
_146
@step_id=1,
_146
@cmdexec_success_code=0,
_146
@on_success_action=3,
_146
@on_success_step_id=0,
_146
@on_fail_action=2,
_146
@on_fail_step_id=0,
_146
@retry_attempts=0,
_146
@retry_interval=0,
_146
@os_run_priority=0, @subsystem=N'TSQL',
_146
@command=N'DECLARE @databaseName nvarchar(max);
_146
DECLARE @sql nvarchar(max);
_146
_146
DECLARE database_cursor CURSOR FOR
_146
SELECT
_146
d.[name],
_146
''ALTER DATABASE ['' + d.[name] + ''] SET RECOVERY SIMPLE;'' AS [Query]
_146
FROM
_146
[sys].[databases] AS d
_146
WHERE
_146
d.[database_id] > 4
_146
AND
_146
d.[recovery_model_desc] != ''SIMPLE''
_146
ORDER BY
_146
d.[name]
_146
_146
OPEN database_cursor
_146
_146
FETCH NEXT FROM database_cursor
_146
INTO @databaseName, @sql
_146
_146
WHILE @@FETCH_STATUS = 0
_146
BEGIN
_146
PRINT ''Altering database '' + @databaseName;
_146
EXEC(@sql)
_146
FETCH NEXT FROM database_cursor
_146
INTO @databaseName, @sql
_146
END
_146
CLOSE database_cursor;
_146
DEALLOCATE database_cursor;',
_146
@database_name=N'master',
_146
@flags=0
_146
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
_146
/****** Object: Step [Shrink Database Files] Script Date: 8/6/2025 12:25:07 PM ******/
_146
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Shrink Database Files',
_146
@step_id=2,
_146
@cmdexec_success_code=0,
_146
@on_success_action=1,
_146
@on_success_step_id=0,
_146
@on_fail_action=2,
_146
@on_fail_step_id=0,
_146
@retry_attempts=0,
_146
@retry_interval=0,
_146
@os_run_priority=0, @subsystem=N'TSQL',
_146
@command=N'DECLARE @databaseName nvarchar(max);
_146
DECLARE @databaseFileName nvarchar(max);
_146
DECLARE @sql nvarchar(max);
_146
_146
DECLARE database_cursor CURSOR FOR
_146
SELECT
_146
d.[name],
_146
mf.[name],
_146
''USE ['' + d.[name] + '']; DBCC SHRINKFILE(N'''''' + mf.[name] + '''''', 0, TRUNCATEONLY);'' AS [Query]
_146
FROM
_146
[sys].[master_files] AS mf
_146
INNER JOIN [sys].[databases] AS d ON
_146
mf.[database_id] = d.[database_id]
_146
WHERE
_146
d.[database_id] > 4
_146
ORDER BY
_146
d.[name]
_146
_146
OPEN database_cursor
_146
_146
FETCH NEXT FROM database_cursor
_146
INTO @databaseName, @databaseFileName, @sql
_146
_146
WHILE @@FETCH_STATUS = 0
_146
BEGIN
_146
PRINT ''Shrinking database file '' + @databaseFileName + '' of database '' + @databaseName;
_146
EXEC(@sql)
_146
FETCH NEXT FROM database_cursor
_146
INTO @databaseName, @databaseFileName, @sql
_146
END
_146
CLOSE database_cursor;
_146
DEALLOCATE database_cursor;',
_146
@database_name=N'master',
_146
@flags=0
_146
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
_146
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
_146
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
_146
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'Daily at 1pm',
_146
@enabled=1,
_146
@freq_type=4,
_146
@freq_interval=1,
_146
@freq_subday_type=1,
_146
@freq_subday_interval=0,
_146
@freq_relative_interval=0,
_146
@freq_recurrence_factor=0,
_146
@active_start_date=20250806,
_146
@active_end_date=99991231,
_146
@active_start_time=130000,
_146
@active_end_time=235959,
_146
@schedule_uid=N'2a890b02-284f-46fd-bab9-dbb267035bd2'
_146
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
_146
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
_146
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
_146
COMMIT TRANSACTION
_146
GOTO EndSave
_146
QuitWithRollback:
_146
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
_146
EndSave:
_146
GO

You should now see this job in SQL Server Management Studio under SQL Server Agent. It is configured to run daily at 1pm, but you can adjust this if needed.

SQL Server Agent Job in Management Studio

You can right click that job and click View History to view the history of the job to make sure it is running without issue. You can also right click it and start it manually (with Start Job at Step…).

Log File Viewer History

Credits

Shout out to my colleague Erik Carron for doing the heavy lifting on this.

Stay lean,

-MG


More Stories

Cover Image for Sitecore Symposium 2022

Sitecore Symposium 2022

> What I'm Watching 👀

Cover Image for Symposium 2022 Reflections

Symposium 2022 Reflections

> Sitecore is making big changes

Cover Image for Troubleshooting 502 Responses in Azure App Services

Troubleshooting 502 Responses in Azure App Services

> App Services don't support all libraries

Cover Image for On Sitecore Development

On Sitecore Development

> Broadly speaking

Cover Image for On Mentorship and Community Contributions

On Mentorship and Community Contributions

> Reflections and what I learned as an MVP mentor

Cover Image for Tips for Forms Implementations

Tips for Forms Implementations

> And other pro tips

Cover Image for Considerations for Hosting Mail Signature Images on Vercel

Considerations for Hosting Mail Signature Images on Vercel

> Outlook is a Cache-Control disrepectoor and that's a problem

Cover Image for NextJS: Unable to Verify the First Certificate

NextJS: Unable to Verify the First Certificate

> UNABLE_TO_VERIFY_LEAF_SIGNATURE

Cover Image for Content Editor Search Bar Not Working

Content Editor Search Bar Not Working

> Sometimes it works, sometimes not

Cover Image for Integrating Cloudflare Turnstile with Sitecore Forms

Integrating Cloudflare Turnstile with Sitecore Forms

> Smack down spam quickly and easily

Cover Image for NextJS/JSS Edit Frames Before JSS v21.1.0

NextJS/JSS Edit Frames Before JSS v21.1.0

> It is possible. We have the technology.

Cover Image for How to Run Old Versions of Solr in a Docker Container

How to Run Old Versions of Solr in a Docker Container

> Please don't make me install another version of Solr on my local...

Cover Image for Year in Review: 2022

Year in Review: 2022

> Full steam ahead

Cover Image for JSS: Reducing Bloat in Multilist Field Serialization

JSS: Reducing Bloat in Multilist Field Serialization

> Because: performance, security, and error-avoidance

Cover Image for SPE Script Performance & Troubleshooting

SPE Script Performance & Troubleshooting

> Script never ends or runs too slow? Get in here.

Cover Image for How to Run Sitecore 10.3.x in Docker on Windows 10

How to Run Sitecore 10.3.x in Docker on Windows 10

> Configs for loading useful asset images

Cover Image for JSS + TypeScript Sitecore Project Tips

JSS + TypeScript Sitecore Project Tips

> New tech, new challenges

Cover Image for Security Series: App Service IP Restrictions

Security Series: App Service IP Restrictions

> How to manage IP rules "at scale" using the Azure CLI

Cover Image for NextJS: Access has been blocked by CORS policy

NextJS: Access has been blocked by CORS policy

> CORS is almost as much of a nuisance as GDPR popups

Cover Image for Tips for New Sitecore Developers

Tips for New Sitecore Developers

> If I had more time, I would have written a shorter letter

Cover Image for Ideas For Docker up.ps1 Scripts

Ideas For Docker up.ps1 Scripts

> Because Docker can be brittle

Cover Image for Add TypeScript Type Checks to RouteData fields

Add TypeScript Type Checks to RouteData fields

> Inspired by error: Conversion of type may be a mistake because neither type sufficiently overlaps with the other.

Cover Image for Super Fast Project Builds with Visual Studio Publish

Super Fast Project Builds with Visual Studio Publish

> For when solution builds take too long

Cover Image for Early Returns in React Components

Early Returns in React Components

> When and how should you return early in a React component?

Cover Image for Azure PaaS Cache Optimization

Azure PaaS Cache Optimization

> App Services benefit greatly from proper configuration

Cover Image for Handy PowerShell Script When Working With Text Fields

Handy PowerShell Script When Working With Text Fields

> Quickly analyze freeform text field inputs

Cover Image for Tips for Applying Cumulative Sitecore XM/XP Patches and Hotfixes

Tips for Applying Cumulative Sitecore XM/XP Patches and Hotfixes

> It's probably time to overhaul your processes

Cover Image for Don't Ignore the HttpRequestValidationException

Don't Ignore the HttpRequestValidationException

> Doing so could be... potentially dangerous

Cover Image for On Sitecore Stack Exchange (SSE)

On Sitecore Stack Exchange (SSE)

> What I've learned, what I see, what I want to see

Cover Image for Script: Boost SIF Certificate Expiry Days

Script: Boost SIF Certificate Expiry Days

> One simple script that definitely won't delete your system32 folder

Cover Image for Critical Security Bulletin SC2024-001-619349 Announced

Critical Security Bulletin SC2024-001-619349 Announced

> And other scintillating commentary

Cover Image for Hello World

Hello World

> Welcome to the show

Cover Image for NextJS: Short URL for Viewing Layout Service Response

NextJS: Short URL for Viewing Layout Service Response

> Because the default URL is 2long4me