Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Shrink and Compact in SQL Server CE?

I have a method that is run periodically to optimise my application's SQL Server Compact Edition (3.5) database. The existing code uses the Shrink() method:

        SqlCeEngine engine = new SqlCeEngine(dbConnectionString);
        engine.Shrink();

Today I noticed that there's also a Compact() method. Which is preferable for periodic maintenance?

like image 585
Paul Beesley Avatar asked Apr 01 '09 22:04

Paul Beesley


People also ask

What is the difference between shrink and compress in SQL Server?

+1 In short: Shrinking just frees and moves pages. Compression actually changes the data on each page.

What is shrinking in SQL Server?

Shrinking data files recovers space by moving pages of data from the end of the file to unoccupied space closer to the front of the file. When enough free space is created at the end of the file, data pages at end of the file can deallocated and returned to the file system.

Is it OK to shrink SQL database?

Many SQL Server experts advise against SQL Server database shrinking, especially as a frequent and pre-scheduled maintenance action. Nevertheless, there are some critical situations where it is considered as the only valid or applicable solution: After a big archiving job. After dropping large amount of tables.

How long does a shrink database take?

Also, this process could take about 20 to 25 minutes, depending on your computer's performance.


1 Answers

From the SQL Server Compact Team Blog:

The difference between these two is much similar to Internal and External Memory Fragmentation.


From SqlCeEngine.Shrink documentation,

Reclaims wasted space in the database by moving empty and unallocated pages to the end of the file, and then truncating the file. You can configure a database to automatically shrink by setting the autoshrink threshold option in connection string. Shrink does not create a temporary database file.

From SqlCeEngine.Compact documentation,

Reclaims wasted space in the database by creating a new database file from the existing file. By creating a new database means, it reclaims the free space between rows.


To be more clear, Shrink claims the pages which are entirely free or unallocated; where as, Compact claims the wasted space with in the page too. Hence Compact requires creating a new database file.

like image 134
Tim Avatar answered Nov 05 '22 17:11

Tim