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.

Syntax

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.

Example

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:

table1

Since there is a table table1 in second_db.sqlite.

Now to detach this database, we run:

DETACH DATABASE 'second';

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:

DETACH DATABASE;

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.

Ray Ferrell is a developer who writes about building and managing databases. He brings over ten years of hands-on experience with SQL and Python to each guide on SQLdocs. He started the site to help other devs solve real problems, not just read about theory. Ray’s work is practical and rooted in code he’s used himself. When not at the keyboard, he’s probably out hiking or learning a new recipe.