SQL database detaching is the process of removing the database from the SQL Server instance without deleting the database files from the disk.
You may come across two different SQL database file types : "Raw Data" files and "Log" files. Raw data files are used to store the actual data of the database with ".mdf" file extension. While log files store a record of all changes made to the database with a ".ldf" file extension.
When you detach a database, it disappears from "Database folder" in object explorer and becomes unavailable to any SQL Server connection. Here's the default SQL Server database file location :
C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\DATA
As you can see in below image, [AdventureWorks2019] database is present. Let's detach it!
1. Run below SQL command in SSMS :
/* Option is set "true" to skip checks */ USE [master]; EXEC sp_detach_db 'AdventureWorks2019', 'true';
2. Above command will detach the [AdventureWorks2019] database from the SQL Server instance.
That's it! You have successfully detached [AdventureWorks2019] database using T-SQL.
1. Right-click on the database you want to detach in "Database folder" >> Select "Tasks" >> Select "Detach".
2. "Detach Database" dialog box will appear, Make sure that the "Drop Connections" option is checked >> Click "OK".
3. There you go, [AdventureWorks2019] database detached successfully.
That's it! You have successfully detached [AdventureWorks2019] database using GUI.
Detaching a SQL database removes it from the SQL Server instance, making its files inaccessible to the server.
You can detach from SQL Server using the "sp_detach_db" stored procedure or through SQL Server Management Studio by right-clicking the database and selecting "Detach".
Detach removes the database entirely from the server, while offline mode temporarily stops access to the database but keeps it attached.
Detaching is useful for transferring databases, performing maintenance, or troubleshooting.