
For an instructor lead, in-depth look at learning SQL click below.
When dealing with SQL Servers, it is crucial to equip yourself with efficient data recovery solutions. One such strategy is the use of database snapshots. A database snapshot is a read-only, static view of a SQL server database (the source database). It’s a valuable tool used for ransacking data, managing reports, and handling data recovery.
Understanding Database Snapshots
Database snapshots work based on a mechanism of ‘copy-on-write’. When the snapshot is created, the pages of the database remain untouched until any modification is made to the pages of the source database. Before any such change, SQL server copies the original page from the source database to the snapshot, ensuring that the snapshot remains a consistent static view of the source database.
Creating a Database Snapshot
1 2 3 4 5 6 |
-- Consider the source database is 'TestDB' CREATE DATABASE TestDB_SnapShot ON ( NAME = TestDB, FILENAME = 'C:\SSMS\TestDB_Snapshot.ss' ) AS SNAPSHOT OF TestDB; |
The above SQL code snippet illustrates how to create a database snapshot named ‘TestDB_SnapShot’ for the source database ‘TestDB’. ‘NAME’ refers to the logical name of the source database, and ‘FILENAME’ is where the snapshot file will be physically stored.
Recovering Data From a Snapshot
Data recovery from a snapshot involves reverting the source database to the state of a database snapshot.
1 2 3 4 |
-- Reverting the TestDB database to the snapshot RESTORE DATABASE TestDB FROM DATABASE_SNAPSHOT = 'TestDB_SnapShot' |
The ‘RESTORE DATABASE’ command reverts ‘TestDB’ to the ‘TestDB_SnapShot’ snapshot. This command returns the database to its state when the snapshot was established, thus providing a recovery solution.
Deleting a Database Snapshot
1 2 3 4 |
-- Deleting the TestDB_Snapshot snapshot DROP DATABASE TestDB_SnapShot; |
To delete a database snapshot, use the ‘DROP DATABASE’ command as shown above. Note that deleting a database snapshot doesn’t affect the source database.
Conclusion
SQL Server Database Snapshots provide a valuable data recovery solution. While it’s not a substitution for traditional backup processes, it offers an efficient way of dealing with data loss. Understanding and effectively using this tool can prove to be a significant advantage in managing SQL servers.