Sunday, December 16, 2007

Shrinking SQL databases

I've got a bunch of SQL databases on my machine. Both from SQL 2000, SQL 2005 and also SQL 2008.

The databases are mainly used for testing customers databases or for development, and the actual data isn't really important.

Over time the .mdf and .ldf files have a tendency to grow to 1-3GB files, and keeps hogging more and more of my C:\-drive. Often the files actually just contain free space as well.

A quick way to shrink the files is to run this - the demo base is called Demo1 in this example:

Use Demo1
CHECKPOINT
DBCC SHRINKFILE (Demo1, 1)
DBCC SHRINKFILE (Demo1_log, 1)

This shrinks the files as much as possible by removing "free space" from the files.

The CHECKPOINT is included since my databases are using the Simple Recovery Model, and that command purges the .ldf file. This is the same as is done when you tell SQL Server to do a backup. Only in this case I just truncate the .ldf file, without performing the actual backup.

The DBCC SHRINKFILE commands try to shrink the two files down to 1MB. The .ldf file will end up being 1MB, but the .mdf actually contains data, so it will become as small as it can without deleting data.

No comments: