SQLite Detach Database

SQLite allows you to attach multiple databases to a single database connection. This allows you to access and query tables across multiple database files. The ATTACH DATABASE statement is used to attach a database.

To detach or unattach a database that was previously attached, you use the DETACH DATABASE statement.


The syntax for detaching a database is:

DETACH DATABASE database_name;

Where database_name is the name that was given to the attached database when it was attached.


To demonstrate, first we will attach a database second_db.sqlite to our connection:

ATTACH DATABASE 'second_db.sqlite' AS 'second';

This attaches second_db.sqlite and gives it the alias second for queries.

We can confirm it is attached by querying the sqlite_master table:

SELECT name FROM sqlite_master WHERE type='table' AND name='table1';

Which would return:


Since there is a table table1 in second_db.sqlite.

Now to detach this database, we run:


If we try querying table1 again, we will get an error since the database is no longer attached.

Detaching All Attached Databases

You can also detach all attached databases at once with:


This will detach every database that was previously attached to the connection.

Reattaching Databases

To reattach a previously detached database, just use the ATTACH DATABASE statement again. The database file path and alias need to match the original attachment.

For example, to reattach our second_db.sqlite, we would run:

ATTACH DATABASE 'second_db.sqlite' AS 'second';

So in summary, the DETACH DATABASE statement allows you to unattach a previously attached database to your SQLite connection. This removes access to those database tables until the database is reattached again.