How to Change a Database Name in SQL Server using T-SQL

When using SQL Server, if you want to change the name of a database, you can do this by using a GUI (like SSMS) or by using Transact-SQL.

If using a GUI, you can right-click on the database name and click Rename to rename the database (you might need to set the database to single-user mode first).

If you’re doing this using T-SQL, the examples on this page should help you out.

Basic Example

Here’s a basic example for changing the name of a database using T-SQL:

USE master;
GO

ALTER DATABASE Problems  
MODIFY NAME = Solutions; 
GO

First we change to the master database, then we use the ALTER DATABASE statement to change the name of the database from Problems to Solutions.

This example also uses GO which, although not strictly T-SQL, is recognised by various utilities as signalling the end of a batch of T-SQL statements.

Rename Data and Log Files

It’s important to note that the previous example doesn’t rename the data and log files. It simply renames the database. The data and log files remain with their original names. In this example, we now have a database called Solutions but with data and log files called something like Problems.mdf and Problems_log.ldf. This is not what we want.

Here’s how we can rename the data files and log files for this database, so that they reflect the name of the database:

-- Change the logical name of the data file
ALTER DATABASE Solutions
MODIFY FILE ( 
  NAME = 'Problems', 
  NEWNAME = 'Solutions' 
  );

-- Change the logical name of the log file
ALTER DATABASE Solutions
MODIFY FILE ( 
  NAME = 'Problems_log', 
  NEWNAME = 'Solutions_log' 
  );

-- Change the physical path of the data file
ALTER DATABASE Solutions
MODIFY FILE ( 
  NAME = 'Solutions', 
  FILENAME = 'D:\mssql\data\Solutions.mdf' 
  );

-- Change the physical path of the log file
ALTER DATABASE Solutions
MODIFY FILE ( 
  NAME = 'Solutions_log', 
  FILENAME = 'D:\mssql\data\Solutions_log.ldf' 
  );  

So we change both the logical names and the physical names of the files.

These file paths are purely for demonstration purposes, you should use whatever file paths are correct for your particular environment.

Also note that this example uses Windows file paths. If you’re using Linux (or Mac), you’ll need to use a forward slash (/) instead of the backslash (\).