Question

I am considering to use LocalDB in future projects, instead of OleDB (MDB).

Do I need to compact database from time to time? And if yes, then how?

I found what there is a Shrink option in case of SQL database (MDF, right?), possibility to define autoshrink and repair somehow. Perhaps I don't need to do a compaction (which in my understanding is creating new database and copying actual content into it, so all outdated content is removed), but it is enough to enable shrinking somehow (which is an option, so that server periodically do a kind of garbage collection, by moving garbage to the end of database file and truncating the file).

It is also interesting, how well shrink works in regards of file system fragmentation (my guess is not very good).

All-in-all I'd prefer to have compaction, the idea (code) of how to perform it and how to determine when it's needed (criteria to perform compaction).

I see, there is BACKUP command, perhaps compacting will looks like: 1) backup 2) recreate database 3) restore from backup?

Was it helpful?

Solution

LocalDB is SQL Server Express, which is SQL Server. General SQL Server guidelines will usually apply to LocalDB as well, unless you have very specific situation. Note that SQL Server Express (including LocalDB) has an additional limit on the MDF file size, which in 10GB in SQL Server Express 2012.

One thing to keep in mind is that the format was designed to be fast, and not compact. For example, an empty database will create an MDF file that is a couple MBs big.

autogrow and autoshrink seem to be the way to go for managing the MDF size, if you want to keep it down as much as possible. There are performance-related trade-offs, discussed in this KB 315512 article and this post by Paul Randall, including the discussion in comments.

As per file system fragmentation - creating the database with big enough file size should help, as the OS should be able to find big continuous block(s) of disk space easier when asked at once. When the database file grows and shrinks it is more likely to be fragmented at the file system level. I found this post as well, discussing using a tool to "manually" defragment a given file. Looks promising, but I have not tested it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top