Loading...

We've detected that your browser language is Chinese. Would you like to visit our Chinese website? [ Dismiss ]
By: Dervish

Backing up a SQL Server database is one of the most important tasks for database administrators and IT teams. While SQL Server Management Studio (SSMS) provides a graphical interface for creating backups, many professionals prefer using T-SQL queries because they are faster, easier to automate, and easier to integrate into maintenance scripts.

Using SQL queries also gives administrators more control over backup operations, making them ideal for scheduled jobs, disaster recovery plans, and enterprise database management.

In this guide, you’ll learn how to backup database in SQL Server using query commands, including full backups, differential backups, transaction log backups, backup verification, and database restoration. Whether you’re a beginner or an experienced DBA, this tutorial will help you create a reliable SQL Server backup strategy.

how-to-backup-database-in-sql-server-using-query

Why Use Queries to Backup SQL Server Databases?

Before learning the backup commands, it’s helpful to understand why many DBAs rely on T-SQL instead of graphical tools.

Faster Administration

Using queries allows administrators to execute backup operations directly without navigating multiple menus in SSMS.

Easier Automation

T-SQL backup commands can be integrated into SQL Server Agent jobs, PowerShell scripts, and enterprise automation workflows.

Better Scalability

Managing backups across multiple databases becomes significantly easier when using standardized scripts.

Prerequisites Before Running SQL Server Backup Queries

Before creating backups, verify that your environment meets the following requirements.

Verify Permissions

The account executing the backup command should have sufficient privileges.

Run the following query:

SQL
SELECT IS_SRVROLEMEMBER('sysadmin'); 
If the result is 1, the account has sysadmin permissions.

Verify Backup Location

Ensure the target directory already exists.

SQL
D:\SQLBackups\ 
Additionally:
  • SQL Server service account must have write permissions.

  • The destination drive should have enough free space.

  • Backup storage should be monitored regularly.

Check Database Size

Estimating database size helps avoid backup failures caused by insufficient storage.

Execute:

SQL
EXEC sp_spaceused;

Review the database size before selecting a backup destination.

How to Backup Database in SQL Server Using Query

The BACKUP DATABASE statement is the primary command used to create SQL Server database backups.

Let’s walk through the process step by step.

Step 1. Create a Full Database Backup

A full backup contains the entire database, including all tables, indexes, stored procedures, and data.

To create a full backup, execute the following query:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Full.bak'
WITH
    FORMAT,
    INIT,
    NAME = 'SalesDB Full Backup';

What This Query Does

BACKUP DATABASE SalesDB

Specifies the database to back up.

TO DISK

SQL
TO DISK = 'D:\SQLBackups\SalesDB_Full.bak'

Defines the location and filename of the backup.

FORMAT

Creates a new media set and removes previous backup headers.

INIT

Overwrites the existing backup file if it already exists.

NAME

Adds a descriptive label to the backup set.

Expected Result

After execution, SQL Server should return a message similar to:

SQL
BACKUP DATABASE successfully processed.

The backup file should now exist in the specified directory.

Step 2. Create a Compressed Backup

Backup compression reduces storage requirements and can improve backup performance.

Run:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Compressed.bak'
WITH COMPRESSION;

Benefits of Compression

  • Smaller backup files

  • Lower storage costs

  • Faster network transfers

  • Easier backup management

Compression is highly recommended for production databases.

Step 3. Verify the Backup File

Creating a backup is not enough. You should always verify that SQL Server can read the backup successfully.

Execute:

SQL
RESTORE VERIFYONLY
FROM DISK = 'D:\SQLBackups\SalesDB_Full.bak';

Expected Result

If the backup is valid, SQL Server returns:

SQL
The backup set on file 1 is valid.

Why Verification Matters

Many administrators assume a successful backup job guarantees recoverability. However, storage issues, corruption, or permission problems can still affect backup files.

Running RESTORE VERIFYONLY helps identify potential issues before a disaster occurs.

Step 4. Check Backup History

SQL Server stores backup history in the MSDB database.

Execute the following query:

SQL
SELECT
    bs.database_name,
    bs.backup_start_date,
    bs.backup_finish_date,
    bs.type,
    bmf.physical_device_name
FROM msdb.dbo.backupset bs
INNER JOIN msdb.dbo.backupmediafamily bmf
ON bs.media_set_id = bmf.media_set_id
ORDER BY bs.backup_finish_date DESC;

Understanding the Results

Backup Type Meaning
D Full Backup
I Differential Backup
L Transaction Log Backup

This query is useful for auditing backup activities and confirming that scheduled jobs are running successfully.

How to Create a Differential Backup Using Query

Full backups provide complete protection, but they can become large and time-consuming.

Differential backups only capture changes made since the most recent full backup.

To create a differential backup, run:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Diff.bak'
WITH DIFFERENTIAL; 

How Differential Backups Work

Consider the following scenario:

Day Backup Type
Monday Full Backup
Tuesday Differential Backup
Wednesday Differential Backup

The Wednesday differential backup contains all changes made since Monday’s full backup.

Recovery Requirements

To restore successfully, you’ll need:

  1. The most recent full backup.

  2. The most recent differential backup.

This approach reduces backup size while maintaining efficient recovery.

How to Backup SQL Server Transaction Logs Using Query

For databases operating under the Full Recovery Model, transaction log backups are essential.

They help minimize data loss and enable point-in-time recovery.

Step 1. Check the Recovery Model

Run:

SQL
SELECT
    name,
    recovery_model_desc
FROM sys.databases
WHERE name = 'SalesDB';

If the result shows FULL, transaction log backups can be created.

Step 2. Create a Transaction Log Backup

Execute:

SQL
BACKUP LOG SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Log.trn';

Benefits of Transaction Log Backups

  • Capture recent transactions

  • Reduce Recovery Point Objectives (RPO)

  • Support point-in-time recovery

  • Prevent excessive transaction log growth

Example Scenario

Imagine:

  • Full backup at midnight

  • Log backups every 15 minutes

  • Database failure at 2:07 PM

Using log backups, you can restore the database to approximately 2:06 PM, minimizing data loss.

How to Restore a SQL Server Database from a Backup File

Creating backups is only half of the recovery process. You should also understand how to restore a database when needed.

Restore a Full Database Backup

To restore a database from a backup file, execute:

SQL
RESTORE DATABASE SalesDB
FROM DISK = 'D:\SQLBackups\SalesDB_Full.bak'
WITH REPLACE;

What This Query Does

RESTORE DATABASE

Specifies the database to restore.

FROM DISK

Defines the backup file location.

WITH REPLACE

Allows SQL Server to overwrite the existing database.

Important Considerations

Before restoring:

  • Ensure no active connections exist.

  • Verify that the backup file is valid.

  • Confirm that the backup is the correct version.

  • Understand that the current database will be overwritten.

Verify the Restored Database

After restoration, run:

SQL
DBCC CHECKDB ('SalesDB');

This command checks database consistency and verifies that the restore operation completed successfully.

How to Automate SQL Server Backups with SQL Server Agent

Manually running backup queries is practical for testing and learning purposes, but production environments require automation to ensure backups are performed consistently and on schedule.

SQL Server Agent allows you to automate backup jobs without requiring manual intervention.

Step 1. Create a New SQL Server Agent Job

In SQL Server Management Studio (SSMS), navigate to:

Object Explorer
→ SQL Server Agent
→ Jobs
→ New Job

Enter a meaningful job name, such as:

Daily Full Database Backup

Using descriptive job names makes future maintenance and troubleshooting easier.

Step 2. Add a Backup Step

Within the new job, select Steps and create a new step.

Choose:

Type: Transact-SQL Script (T-SQL)
Database: master

Then enter your backup query:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Full.bak'
WITH
    COMPRESSION,
    INIT;

Save the step.

Step 3. Configure a Schedule

Select Schedules and create a new schedule.

Common examples include:

Environment Recommended Schedule
Development Daily
Small Business Daily Full Backup
Enterprise Production Full + Differential + Log Backups

For example:

Daily at 11:00 PM

or

Every Sunday at 1:00 AM

The optimal schedule depends on business requirements and acceptable data loss windows.

Step 4. Test the Job

Before relying on the schedule, run the job manually.

Verify:

  • Backup file creation

  • Successful job completion

  • No permission errors

  • Sufficient storage space

Automation reduces the risk of missed backups and ensures consistent protection.

Common SQL Server Backup Query Errors and Solutions

Even simple backup operations can fail if the environment is not configured correctly.

The following are some of the most common backup-related errors and their solutions.

Operating System Error 5 (Access Is Denied)

Typical Error Message

Operating system error 5 (Access is denied).

Cause

The SQL Server service account lacks write permissions to the target directory.

Solution

Verify the SQL Server service account:

SELECT servicename, service_account
FROM sys.dm_server_services;

Grant write access to the backup directory and retry the backup.

Backup Device Cannot Be Opened

Typical Error Message

Cannot open backup device.
Operating system error 3.

Cause

The specified folder does not exist or the file path is incorrect.

For example:

D:\SQLBackups\

may not exist on the server.

Solution

Verify:

  • Directory exists

  • Drive letter is correct

  • SQL Server can access the location

Insufficient Disk Space

Typical Error Message

There is insufficient free space on disk volume.

Cause

The backup destination does not have enough available storage.

Solution

Consider:

  • Deleting obsolete backup files

  • Expanding storage capacity

  • Using backup compression

  • Implementing backup retention policies

Transaction Log Backup Fails

Typical Error Message

BACKUP LOG cannot be performed because there is no current database backup.

Cause

A transaction log backup requires an existing full backup.

Solution

First create a full backup:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Full.bak';

Then run the log backup again.

SQL Server Backup Query Best Practices

Creating backups is important, but following best practices is what ensures successful recovery when an outage occurs.

Store Backups on Separate Storage

Never store backups on the same disk as the production database.

If the storage device fails, both the database and backup files could be lost.

A better approach is:

Production Database
    ↓
Dedicated Backup Storage
    ↓
Offsite or Cloud Storage

This aligns with the widely adopted 3-2-1 backup strategy.

Regularly Test Restore Procedures

Many organizations verify backups but never test actual recovery.

At regular intervals:

  1. Restore backups to a test server.

  2. Validate application functionality.

  3. Confirm data integrity.

A backup that cannot be restored provides no protection.

Combine Full, Differential, and Log Backups

Relying exclusively on full backups often increases backup windows and storage requirements.

A common strategy is:

Backup Type Frequency
Full Backup Weekly
Differential Backup Daily
Log Backup Every 15–30 Minutes

This approach balances recovery speed and storage efficiency.

Monitor Backup Jobs

Failed backup jobs should never go unnoticed.

Monitor:

  • Job failures

  • Backup duration

  • Storage consumption

  • Backup completion status

Early detection prevents recovery surprises during an outage.

Encrypt Sensitive Backups

If backups contain customer information, financial records, or regulated data, encryption should be enabled.

Example:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Encrypted.bak'
WITH ENCRYPTION
(
    ALGORITHM = AES_256,
    SERVER CERTIFICATE = BackupCertificate
);

Encryption helps protect backup files from unauthorized access.

Limitations of Manual SQL Backup Queries

T-SQL provides excellent flexibility for database backups. However, as environments grow, managing backups manually becomes increasingly difficult.

Common challenges include:

Multiple SQL Server Instances

Organizations often manage dozens or even hundreds of databases across different servers.

Maintaining backup scripts for each instance can quickly become complex.

Limited Centralized Visibility

T-SQL scripts do not provide a unified dashboard for monitoring backup status across environments.

Administrators may need to manually review job histories and logs.

Recovery Complexity

Recovering large environments frequently requires:

  • Identifying the correct backup chain

  • Restoring multiple files

  • Verifying recovery consistency

This can be time-consuming during critical outages.

Increased Risk of Human Error

Manual maintenance introduces risks such as:

  • Incorrect file paths

  • Missing backup jobs

  • Misconfigured retention settings

  • Failed backup verification

These issues become more common as environments scale.

Simplify SQL Server Backup and Recovery with i2Backup

For organizations managing business-critical databases, backup success is only part of the challenge. Centralized management, monitoring, compliance, and recovery speed are equally important.

This is where i2Backup can complement traditional SQL Server backup methods.

What Is i2Backup?

i2Backup is an enterprise backup and recovery solution designed to protect databases, physical servers, virtual machines, applications, and cloud workloads from a single management platform.

Rather than relying entirely on manually maintained backup scripts, administrators can manage backup operations through a centralized interface.

FREE Trial for 60-Day

Why Organizations Use i2Backup for SQL Server Protection

Automated Backup Scheduling

Backup tasks can be scheduled and managed centrally, reducing administrative overhead.

Centralized Management

Administrators gain visibility across multiple SQL Server instances without managing separate scripts for each environment.

Incremental Backup Capabilities

By backing up only changed data, organizations can reduce storage consumption and improve backup efficiency.

Faster Recovery Operations

Streamlined recovery workflows help reduce downtime during outages and data loss incidents.

Unified Data Protection

In addition to SQL Server, organizations can protect virtual machines, file systems, and other critical workloads from the same platform.

When to Choose i2Backup Instead of Manual Queries

The following comparison highlights scenarios where a dedicated backup platform may provide additional value.

Scenario Manual T-SQL Queries i2Backup
Single Development Database
Small Test Environment
Multiple SQL Server Instances
Enterprise Production Environment
Compliance Requirements
Centralized Backup Monitoring
Multi-Workload Protection
Automated Recovery Management

For many organizations, T-SQL remains a useful tool for creating backups, while centralized platforms help simplify management and recovery at scale.

FAQs of How to Backup Database in SQL Server Using Query

How do I backup a SQL Server database using a query?

Use the BACKUP DATABASE command:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Full.bak';

This creates a full backup of the specified database.

What is the SQL query for a full database backup?

A common example is:

SQL
BACKUP DATABASE SalesDB
TO DISK = 'D:\SQLBackups\SalesDB_Full.bak'
WITH COMPRESSION;

This creates a compressed full backup file.

How do I restore a SQL Server database from a backup file?

Execute:

SQL
RESTORE DATABASE SalesDB
FROM DISK = 'D:\SQLBackups\SalesDB_Full.bak'
WITH REPLACE;

This restores the database from the specified backup file.

Can I automate SQL Server backup queries?

Yes. SQL Server Agent allows administrators to schedule backup jobs that run automatically at predefined intervals.

What is the difference between full and differential backups?

A full backup contains the entire database.

A differential backup contains only changes made since the most recent full backup.

How do I verify a SQL Server backup file?

Use:

SQL
RESTORE VERIFYONLY
FROM DISK = 'D:\SQLBackups\SalesDB_Full.bak';

This validates the backup file without restoring the database.

Are SQL queries better than SSMS for backups?

Both methods create the same backup files. However, T-SQL queries are generally preferred for automation, scripting, and large-scale database administration.

Conclusion

Learning how to backup database in SQL Server using query commands is an essential skill for database administrators and IT professionals. By mastering T-SQL backup operations, you can create full backups, differential backups, transaction log backups, verify backup integrity, automate backup schedules, and restore databases when recovery is required.

However, creating backups is only one part of a complete data protection strategy. Organizations must also monitor backup success, verify recoverability, manage retention policies, and reduce recovery times during outages.

For smaller environments, native SQL Server backup queries may be sufficient. For larger or more complex infrastructures, solutions such as i2Backup can help simplify backup management, improve operational efficiency, and strengthen overall data protection.

A core member of info2soft's technical team, specializing in enterprise data management and IT operations. Focused on data backup, disaster recovery solutions, and product iteration optimization, he breaks down technical challenges with practical experience to deliver highly implementable content.

More Related Articles

Table of Contents:
Stay Updated on Latest Tips
Subscribe to our newsletter for the latest insights, news, exclusive content. You can unsubscribe at any time.
Subscribe
Ready to Enhance Business Data Security?
Start a 60-day free trial or view demo to see how Info2soft protects enterprise data.
{{ country.name }}
Please fill out the form and submit it, our customer service representative will contact you soon.
By submitting this form, I confirm that I have read and agree to the Privacy Notice.
{{ isSubmitting ? 'Submitting...' : 'Submit' }}