You can back up a SQL Server database using the command line with sqlcmd or osql (legacy), but the most reliable method is the BACKUP DATABASE T-SQL command executed via sqlcmd or directly in SQL Server Management Studio (SSMS) using its integrated scripting. This method requires no GUI and works in automated scripts or scheduled jobs. Below, we focus on the pure command-line approach—no SSMS needed—along with prerequisites and common pitfalls.
What You'll Need
- A SQL Server instance with sysadmin permissions (or a user with backup rights).
- The
sqlcmdutility installed on the machine where you run the command. This comes with SQL Server native tools (checkC:\Program Files\Microsoft SQL Server\150\Tools\Binnfor SQL Server 2019+ or similar paths for older versions). - A Windows machine (or WSL/WSL2) with SQL Server tools access. Linux support requires
sqlcmdvia Docker or SQL Server on Linux. - A backup directory on the local machine or a network share with write permissions. SQL Server cannot back up to a remote file share unless configured explicitly (use UNC paths with caution).
- Optional: A login script or scheduled task to automate the backup (e.g., via Task Scheduler).
Step-by-Step: Backup a SQL Server Database via Command Line
-
Open Command Prompt as Administrator
Press Win + X, select "Command Prompt (Admin)" or "Windows Terminal (Admin)" to ensure proper permissions and access to
sqlcmd. On Linux/macOS, usesudoor ensure your user has SQL Server tool permissions. -
Navigate to the SQL Server tools directory
Run
cd "C:\Program Files\Microsoft SQL Server\150\Tools\Binn"(adjust the version number if you're using SQL Server 2017 or earlier). Verifysqlcmdis recognized by typing:sqlcmd -V
This should return the SQL Server version (e.g., "Microsoft SQL Server 2022 (RTM)"). -
Connect to your SQL Server instance
Use the following syntax to connect (replace placeholders):
sqlcmd -S
Examples:-U -P -d master - Local instance:
sqlcmd -S localhost -U sa -P YourStrongPassword - Named instance:
sqlcmd -S server\INSTANCENAME -U user -P password - Windows Authentication:
sqlcmd -S server -E(omit-Uand-Pfor trusted auth).
services.msc), or use-Lto list available servers. - Local instance:
-
Execute the BACKUP DATABASE command
Once connected, run the backup command. Example to back up the
AdventureWorksdatabase toD:\Backups\AdventureWorks.bak:BACKUP DATABASE AdventureWorks TO DISK = 'D:\Backups\AdventureWorks.bak' WITH FORMAT, INIT, NAME = 'FullBackup', DESCRIPTION = 'Daily full backup';
Key options:Option Purpose WITH FORMATCreates a new backup media set (required for the first backup to a file). INITOverwrites the backup file if it exists (use NOINITto append to an existing file).NAME = 'Name'Labels the backup for identification in SQL Server logs. DESCRIPTION = 'Desc'Adds a description (visible in SSMS Backup History). COMPRESSIONReduces backup file size (requires SQL Server 2012+). STATS = 10Shows progress every 10% (optional but helpful for large databases). -
Exit sqlcmd
Type
quitor press Ctrl + Z, then Enter to exit the interactive session.
Automating Backups via Batch Script
To run backups automatically, save the above commands to a batch file (e.g.,sql_backup.bat) with the following template:
@echo off sqlcmd -S server\INSTANCE -U user -P password -d master -i "C:\backups\backup_script.sql"In
backup_script.sql, include:
BACKUP DATABASE AdventureWorks TO DISK = 'D:\Backups\AdventureWorks_$(date +%Y%m%d).bak' WITH COMPRESSION, STATS = 10;Schedule this batch file via Task Scheduler (e.g., daily at 2 AM).
Common Mistakes
-
Forgetting permissions
The user must have
BACKUP DATABASErights. Check with:sp_helprotect AdventureWorks
To grant rights temporarily:GRANT BACKUP DATABASE TO [username];
-
Using relative paths
Always use absolute paths (e.g.,
C:\Backups\file.bak) to avoid "File not found" errors. Verify the directory exists before running the backup. -
Skipping WITH FORMAT on new files
Omitting
WORMATon the first backup to a file will fail with "Media set already exists." UseNOFORMATfor subsequent backups to the same file. -
Not testing backups
A backup file with a zero-byte size is useless. Always verify with:
RESTORE VERIFYONLY FROM DISK = 'D:\Backups\file.bak';
-
Ignoring error handling
Large databases may fail silently. Add error handling to your script:
IF %ERRORLEVEL% NEQ 0 ( echo Backup failed! Check logs. exit /b 1 )
Tips for Better Backups
-
Use differential and transactional backups
For critical databases, combine full backups with differential (
BACKUP DATABASE ... WITH DIFFERENTIAL) and transactional (BACKUP LOG) backups to reduce restore time. -
Encrypt backup files
Add
ENCRYPTION ONto protect sensitive data (requires a certificate in SQL Server). Example:BACKUP DATABASE ... WITH ENCRYPTION ON (ALGORITHM = AES_256);
-
Log backup progress
Redirect output to a log file for auditing:
BACKUP DATABASE ... WITH STATS = 10 > D:\Backups\backup_log.txt
-
Test restores regularly
Use
RESTORE DATABASE AdventureWorks FROM DISK = 'path' WITH REPLACEto test your backups in a non-production environment. - Avoid UNC paths (unless necessary) Backups to network shares can fail if the share is unavailable. Use local paths or a dedicated backup server.
Troubleshooting
Backup fails with "Operating system error 5 (Access is denied)."
- Verify the backup directory exists and your user has write permissions (right-click folder > Properties > Security).
- Check for antivirus exclusions—some security software blocks SQL Server backups.
- Run Command Prompt as Administrator (as in Step 1).
Error: "The backup set holds a backup of a database other than the existing database."
This occurs when you try to overwrite a backup file with INIT but the existing file is from a different database. Either:
- Use
NOINITto append to the file (risky if the file is corrupted), or - Delete the old backup file before running the new backup.
Backup hangs or takes excessively long.
- Check for disk I/O bottlenecks (use
Performance Monitorto monitor disk queue length). - Split the backup into multiple files using
TO DISK = 'file1.bak', 'file2.bak'. - Use
COMPRESSIONto reduce the backup size and time. - Verify sufficient free disk space (SQL Server requires ~1.5x the database size for backups).
sqlcmd command not found.
- Ensure SQL Server tools are installed (check
Program Files\Microsoft SQL Server). - Add the tools directory to your system
PATHin Environment Variables. - Use the full path to
sqlcmd.exe(e.g.,"C:\Path\To\sqlcmd.exe").
Backup file is empty (0 KB).
- Verify the database exists and is online (
RESTORE FILELISTONLY FROM DISK = 'file.bak'). - Check for disk full errors or permission issues on the backup location.
- Try backing up to a different location to rule out storage problems.
- Use
STATS = 1to see if the backup process starts at all.
Task Scheduler job fails silently.
- Check the
Historytab in Task Scheduler for the last run status. - Redirect output to a log file in the batch script (e.g.,
> C:\logs\backup.log 2>&1). - Ensure the user account running the task has SQL Server login permissions.
- Test the command manually from the same account to isolate the issue.
Frequently Asked Questions
Can I back up to a remote network share?
Yes, but with caution. Use a UNC path (e.g., \server\share\backup.bak) and ensure:
- The SQL Server service account has read/write access to the share.
- The share is accessible during backup (network issues will fail the backup).
- Consider using
NOINITto avoid overwriting existing files on the share.
How do I back up multiple databases in one command?
Use a loop in a batch file or T-SQL script. Example for databases DB1 and DB2:
sqlcmd -S server -U user -P password -Q " BACKUP DATABASE DB1 TO DISK = 'D:\Backups\DB1.bak' WITH INIT; BACKUP DATABASE DB2 TO DISK = 'D:\Backups\DB2.bak' WITH INIT;"For dynamic queries (all user databases), use:
sqlcmd -S server -U user -P password -Q "
DECLARE @dbname nvarchar(128);
DECLARE db_cursor CURSOR FOR SELECT name FROM sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @dbname;
WHILE @@FETCH_STATUS = 0 BEGIN
EXEC('BACKUP DATABASE [' + @dbname + '] TO DISK = ''D:\Backups\' + @dbname + '.bak'' WITH INIT');
FETCH NEXT FROM db_cursor INTO @dbname;
END
CLOSE db_cursor;
DEALLOCATE db_cursor;"
What’s the difference between FULL, DIFFERENTIAL, and TRANSACTIONAL backups?
- FULL backup: Copies all database files. Slow but restores quickly. Use daily or weekly.
- DIFFERENTIAL backup: Copies changes since the last full backup. Faster than full but requires the full backup to restore.
- TRANSACTIONAL (LOG) backup: Copies transaction logs. Critical for point-in-time recovery but alone cannot restore the full database.
-- Weekly full backup BACKUP DATABASE DB TO DISK = 'full.bak' WITH FULL; -- Daily differential backup BACKUP DATABASE DB TO DISK = 'diff.bak' WITH DIFFERENTIAL; -- Hourly transactional backup BACKUP LOG DB TO DISK = 'log.bak' WITH TRUNCATE_ONLY;
How do I restore a database from a backup taken via command line?
Use RESTORE DATABASE in sqlcmd. Example:
RESTORE DATABASE AdventureWorks FROM DISK = 'D:\Backups\AdventureWorks.bak' WITH REPLACE, STATS = 10;Key options:
REPLACE: Overwrites the existing database (use cautiously).MOVE 'LogicalName' TO 'PhysicalPath': Specifies new file locations if the backup used different paths.NORECOVERY: Leaves the database in a restoring state (useful for chained restores).
Can I automate backups without Task Scheduler?
Yes, use:
- SQL Server Agent Jobs: Create a job in SSMS to run a T-SQL script or batch file.
- PowerShell: Script the backup with
Invoke-Sqlcmdand schedule via PowerShell'sSchedule-Jobor Task Scheduler. - Linux/macOS cron: Use
sqlcmdin a cron job (e.g.,0 2 * * * /usr/bin/sqlcmd -S server -d master -Q "BACKUP DATABASE DB TO DISK = '/backups/db.bak'").
What’s the maximum size of a SQL Server backup file?
The theoretical limit is 2 TB for a single backup file (due to file system constraints), but practical limits depend on:
- The database size (larger databases require more time to back up).
- Available disk space (SQL Server needs ~1.5x the database size for temporary files).
- Network bandwidth (for remote backups).
- Splitting backups into multiple files (e.g.,
TO FILE1, FILE2). - Using compression (
WITH COMPRESSION) to reduce file size. - Backing up to tape or cloud storage (SQL Server supports Azure Blob Storage via
TO URL).