SQLite Detach Database

Here we will learn how to use SQLite detach database statement to detach or disassociate database from current connection with example.

SQLite Detach Database

In SQLite detach database command allows you to dissociate database from the current connection. The database which we are trying to detach is the one which we already opened with the ATTACH DATABASE command.

 

In case if the same database file has been attached multiple times in SQLite then the detach database statement will only detach mentioned name instance and the remaining attachments will continue with the current session.

 

If we use SQLite detach command on the database which is an in-memory or temporary, the database will be destroyed and the content will be lost completely.

 

In SQLite, we cannot detach main or temp databases. The DETACH command will fail if issued inside a transaction.

Syntax of SQLite Detach Database

Following is the syntax of using the SQLite detach database statement.

 

DETACH DATABASE 'database_alias_name';

Here database_alias_name is the alias name of the database that we give as a name for the database when using ATTACH DATABASE command.

Example of SQLite Detach Database

First, we will see what are the databases available in current connection for that run .databases command.

 

sqlite> .databases

When we run .databases command it returns the following databases that are available in the current connection.

 

seq  name             file

---  ---------------  ----------------------------

0    main             C:\sqlite\emp.db

2    myDB             c:\sqlite\db1.db

3    emp              c:\sqlite\emp.db

4    empDB            c:\sqlite\emp.db

Now, if you want to detach database named empDB then run following command.

 

sqlite> DETACH DATABASE empDB;

Now, again we will fire .databases meta-command to see the list of attached databases in the current connection.

 

sqlite> .databases

When we run the above command it returns the following list of databases available in the current connection.

 

seq  name             file

---  ---------------  --------------------------

0    main             C:\sqlite\emp.db

2    myDB             c:\sqlite\db1.db

3    emp              c:\sqlite\emp.db

This is how we can use sqlite detach database statement to detach or disassociate database from current connection.