Back to all posts

Database Backup in SQL Server

In SQL Server, taking a database backup is crucial for data recovery and protection. Here’s a basic guide on how to perform a database backup and restore i…

In SQL Server, taking a database backup is crucial for data recovery and protection. Here’s a basic guide on how to perform a database backup and restore in SQL Server:

Types of Backups:

  1. Full Backup: Backs up the entire database.
  2. Differential Backup/Incremental: Backs up only the data that has changed since the last full backup.
  3. Transaction Log Backup: Backs up the transaction logs, allowing for point-in-time recovery.

How to Perform a Backup

1. Using SQL Server Management Studio (SSMS):

  • Full Backup:
    1. Open SQL Server Management Studio.
    2. Connect to your database instance.
    3. In Object Explorer, expand the Databases node and right-click the database you want to back up.
    4. Select TasksBack Up.
    5. In the Back Up Database dialog:
      • Backup type: Select Full.
      • Destination: Choose a location to store the backup file.
    6. Click OK to start the backup.
  • Differential Backup:
    1. Repeat the steps for a full backup but select Differential as the backup type.
  • Transaction Log Backup:
    1. Follow the same steps and select Transaction Log as the backup type.

2. Using T-SQL:

You can also back up databases using SQL commands in Query Editor:

SQL
--Full Backup: 
BACKUP DATABASE [YourDatabaseName] TO DISK = 'C:\Backup\YourDatabaseName.bak' WITH FORMAT;

--Differential Backup: 
BACKUP DATABASE [YourDatabaseName] TO DISK = 'C:\Backup\YourDatabaseName_diff.bak' WITH DIFFERENTIAL;

--Transaction Log Backup:
BACKUP LOG [YourDatabaseName] TO DISK = 'C:\Backup\YourDatabaseName_log.trn';

Backup Considerations:

  • Backup Storage Location: Ensure enough space is available on the drive where backups are stored.
  • Scheduling Backups: For automated backups, use SQL Server Agent to schedule jobs for regular backups.
  • Restoring a Backup: You can restore a database using SSMS or T-SQL, similar to how backups are created.

Explanation of Key Steps

  • NO RECOVERY Option: The NORECOVERY option is used to keep the database in a restoring state after each restore operation, allowing subsequent log backups to be applied.
  • STOPAT Option: The STOPAT option specifies the exact point in time to which the database should be restored. This is useful when you need to restore to a specific moment, such as just before an accidental data deletion or corruption.

Important Notes:

  • Backup Order: Ensure that you restore the full backup first, followed by all the transaction log backups in the correct order. Any missing backup or wrong sequence will cause the restoration to fail.
  • Backup Time Format: Use the correct time format (e.g., 'yyyy-mm-ddTHH:MM:SS') for the STOPAT option to specify the exact point in time.
  • Validation: After restoring, validate the database to ensure it is in the desired state and that no transactions beyond the specified point in time were applied.

Transaction Log Backup Explained with Real-Time Examples

A Transaction Log Backup captures all the transactions that have occurred since the last transaction log backup. It is essential for databases operating in Full or Bulk-Logged Recovery Model and enables you to restore the database to a specific point in time, providing the capability for point-in-time recovery.

Real-Time Scenario for Transaction Log Backup

Imagine you are a database administrator for an e-commerce platform, and your company's database is running in the Full Recovery Model. The database is constantly being updated with transactions like customer orders, payments, inventory updates, etc.

Scenario: E-Commerce Database Recovery

  1. Full Backup at Midnight:
  • A Full Backup of the database is scheduled every night at midnight. This backup captures the entire state of the database at that point in time.
  1. Transaction Log Backup Every Hour:
  • To minimize data loss and enable point-in-time recovery, Transaction Log Backups are scheduled to occur every hour (e.g., 1:00 AM, 2:00 AM, 3:00 AM, etc.).
  • These backups record all transactions that occurred since the last transaction log backup, capturing changes such as:
    • Orders placed by customers.
    • Payments processed.
    • Inventory updates for products sold or restocked.
  1. Database Corruption at 3:30 AM:
  • At 3:30 AM, the database encounters corruption or failure due to a hardware issue or an unexpected software crash.
  • The goal is to restore the database to its state at 3:29 AM—just before the failure occurred.

Steps to Restore Using Transaction Log Backups

To restore the database to the exact state before the failure, you will use a combination of the Full Backup and the Transaction Log Backups:

Restore the Full Backup:

  • Start by restoring the Full Backup taken at midnight:
    sql RESTORE DATABASE FROM DISK = 'C:\Backup\ECommerceDB_Full.bak' WITH NORECOVERY; -- Keeps the database in a restoring state

Restore the Hourly Transaction Log Backups:

  • Then, restore each Transaction Log Backup in sequence:
SQL
--Restore the log backup from 1:00 AM:
RESTORE LOG [ECommerceDB] FROM DISK = 'C:\Backup\ECommerceDB_Log_1AM.trn' WITH NORECOVERY;

--Restore the log backup from 2:00 AM:
RESTORE LOG [ECommerceDB] FROM DISK = 'C:\Backup\ECommerceDB_Log_2AM.trn' WITH NORECOVERY;

--Restore the log backup from 3:00 AM:
RESTORE LOG [ECommerceDB] FROM DISK = 'C:\Backup\ECommerceDB_Log_3AM.trn' WITH NORECOVERY;

Point-in-Time Recovery:

  • Finally, restore The 3:00 AM transaction log backup file contains all transactions up to 3:00 AM. You use the STOPAT option to tell SQL Server to stop restoring when it reaches 3:29 AM.
PHP
RESTORE LOG [ECommerceDB] FROM DISK = C:\Backup\ECommerceDB_Log_330AM.trn' 
WITH STOPAT = '2024-09-12T03:29:00', RECOVERY; -- Recover to 3:29 AM

No transactions were logged after 3:00 PM. If this is the case, we will get backup only till 3:00 PM. If we had a backup till 4:00 PM, we could have taken backup till 3:29.

Benefits of Using Transaction Log Backups

  1. Minimizing Data Loss: By taking regular transaction log backups, you reduce the amount of data lost in the event of a failure. Only the transactions between the last log backup and the failure may be lost.
  2. Point-in-Time Recovery: Transaction log backups enable you to restore the database to a specific point in time, which is crucial for recovering from data corruption or human errors.
  3. Efficient Backups: Transaction log backups are smaller and faster than full backups, making them suitable for frequent backups.

Practical Example: Why Transaction Log Backups are Important

  • Accidental Deletion of Data:
    Suppose at 3:15 AM, a developer accidentally deletes critical customer records from the database. With a Full Backup taken at midnight and Transaction Log Backups every hour, you can restore the database to 3:14 AM to recover the lost data without losing significant other transactions.
  • Ransomware Attack:
    If a ransomware attack corrupts the database at 2:45 AM, you can restore the Full Backup and apply all the transaction logs up to 2:44 AM, ensuring minimal data loss.

Python
Backup database [AdventureWorksDW2022] to disk = 'D:\BackupTest\DBName\DbName_backuptype_Datetime_bak'
with compression,stats = 10;

WITH COMPRESSION:

  • This option enables compression for the backup file.
  • Compression reduces the size of the backup file, saving disk space and potentially speeding up the backup process. However, it may increase CPU usage during the backup operation.

STATS = 10:

  • This option provides a progress report of the backup operation.
  • STATS = 10 means that SQL Server will report the progress of the backup operation every 10% of completion. For example, it will display progress updates at 10%, 20%, 30%, and so on, up to 100%.
https://youtu.be/z2WW91bkeKM?si=u5rEDVbsucaAPFl-
https://youtu.be/h4n5KwixSvo?si=5u537Ccoff2dUdcV

Restore with MOVE

When restoring a database in SQL Server, the WITH MOVE option is used to specify a new location for the database files (data and log files) if the original file paths are not available or need to be changed. This is particularly useful in scenarios such as:

  • Restoring a database to a different server or environment where the directory structure is different.
  • Moving a database to a new location on the same server (e.g., moving to a different drive for storage optimization).

Syntax for Restore with MOVE

SQL
RESTORE DATABASE 
FROM DISK = 'C:\Backup\YourDatabaseName'
WITH 
   MOVE 'LogicalDataFileName' TO 'D:\NewPath\YourDatabaseName_Data.mdf',
   MOVE 'LogicalLogFileName' TO 'D:\NewPath\YourDatabaseName_Log.ldf',
   RECOVERY;
  1. WITH MOVE:
  • The WITH MOVE clause is used to relocate the data and log files to new paths during the restore operation.
  • This clause requires the logical names of the files within the backup and the new physical file paths where you want to restore these files.

Example Scenario: Restore with MOVE

Suppose you have a backup file of a database named SalesDB, and you want to restore it to a new server. On this new server, the directory structure is different. The original data and log files were stored at:

  • Data file: C:\MSSQL\Data\SalesDB_Data.mdf
  • Log file: C:\MSSQL\Log\SalesDB_Log.ldf

But on the new server, you want to store them at:

  • New data file location: D:\SQLData\SalesDB_Data.mdf
  • New log file location: D:\SQLLogs\SalesDB_Log.ldf

You would use the following RESTORE command with MOVE:

SQL
RESTORE DATABASE [SalesDB]
FROM DISK = 'C:\Backup\SalesDB'
WITH 
   MOVE 'SalesDB_Data' TO 'D:\SQLData\SalesDB_Data.mdf',
   MOVE 'SalesDB_Log' TO 'D:\SQLLogs\SalesDB_Log.ldf',
   RECOVERY;

How to Find Logical File Names

To find the logical names (SalesDB_Data and SalesDB_Log in the example), you can run the following command:

Java
RESTORE FILELISTONLY 
FROM DISK = 'backup file location';

This will return a result set with the logical names of the files stored in the backup, which are required for the WITH MOVE option.

https://youtu.be/HIDmaK-BzMg?si=8d_pW3GuTe4eYa4P

Copy-Only Backup

A Copy-Only Backup is a special type of backup in SQL Server that does not affect the normal backup and restore sequence for the database. It is used to create a backup for a specific purpose, such as copying a database to another environment for testing or performing a one-time backup without disturbing the regular backup schedule.

Key Features of a Copy-Only Backup

Does Not Affect the Backup Chain: Unlike regular full or differential backups, a copy-only backup does not impact the sequence of regular backups (the backup chain). This is crucial in environments where regular backups are part of a carefully managed backup strategy.

When to Use a Copy-Only Backup

  • One-Time Backups for Specific Needs: When you need to create a backup for a specific purpose (e.g., moving the database to a different environment, creating a backup for development or testing) without interfering with the regular backup strategy.
  • Data Migration: For example, if you need to migrate a database to another server or environment but don’t want to disrupt the existing backup routines.
  • Database Snapshots: To create a point-in-time snapshot of a database for reporting or auditing purposes without affecting the backup schedule.
  • Avoiding Backup Chain Disruption: When performing maintenance tasks or troubleshooting and you need to take a backup without changing the backup chain.

How to Create a Copy-Only Backup

You can create a copy-only backup using either SQL Server Management Studio (SSMS) or T-SQL.

1. Using SQL Server Management Studio (SSMS)

To perform a copy-only backup in SSMS:

  1. Open SQL Server Management Studio and connect to the database instance.
  2. In Object Explorer, expand the Databases node.
  3. Right-click on the database you want to back up and select TasksBack Up….
  4. In the Back Up Database dialog:
  • Backup type: Select Full or Transaction Log depending on your needs.
  • Copy-only Backup: Check the Copy-only Backup checkbox to specify that this is a copy-only backup.
  • Destination: Choose the destination where the backup will be stored.
  1. Click OK to start the backup.

2. Using T-SQL

You can also create a copy-only backup using T-SQL commands.

  • Copy-Only Full Backup:
Java
   BACKUP DATABASE 
   TO DISK = 'C:\Backup\YourDatabaseName_CopyOnly.bak'
   WITH COPY_ONLY, COMPRESSION, STATS = 10;
  • COPY_ONLY: Specifies that this is a copy-only backup.
  • COMPRESSION: (Optional) Compresses the backup to save storage space.
  • STATS = 10: (Optional) Reports the progress of the backup every 10%.
  • Copy-Only Transaction Log Backup:
Java
   BACKUP LOG 
   TO DISK = 'C:\Backup\YourDatabaseName_Log_CopyOnly.trn'
   WITH COPY_ONLY, STATS = 10;
  • COPY_ONLY: Ensures that this log backup does not affect the log chain or truncate the transaction logs.
  • STATS = 10: (Optional) Provides progress updates.

Copy-Only Backup:

  • Full Copy-Only Backup:
Java
   BACKUP DATABASE 
   TO DISK = 'C:\Backup\YourDatabaseName_CopyOnly.bak'
   WITH COPY_ONLY;

This creates a full backup of the database without affecting the differential backup sequence.

  • Copy-Only Transaction Log Backup:
Java
   BACKUP LOG 
   TO DISK = 'C:\Backup\YourDatabaseName_Log_CopyOnly.trn'
   WITH COPY_ONLY;

This backs up the transaction log without truncating it or affecting the normal log backup chain.

https://youtu.be/yIgFzCwVcXQ?si=lhzJ3Nxr_d7Y0UWn
https://youtu.be/3MnHNMhC3HU?si=SuLUVD6SfVplh9iF
https://youtu.be/8y9APrcsHwc?si=9Ck97PgdS_3y39Ty

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.