Attach a Database in SQLite

When using SQLite, you can use the ATTACH DATABASE statement to add a database file to the current database connection.

When you do this, you attach a database file name and provide a name for the database. If the file exists it will be attached with your chosen name, otherwise it will be created and attached with your chosen name.

Example

ATTACH DATABASE 'Pets.db' AS Pets;

This example causes the Pets.db database file to be attached and called Pets.

You can use .databases to check that it has been attached.

.databases

Result:

main: /Users/Shared/Pets.db
Pets: /Users/Shared/Pets.db

In this case, I’d previously added this database under main, so the same database file is now attached under two different names.

The name is the name of the database used internally by SQLite.

Detach a Database

You can use DETACH DATABASE to detach a database from the current connection. This doesn’t delete the database file, it simply removes the database from your connection.

DETACH DATABASE Pets;

Check again:

.databases

Result:

main: /Users/Shared/Pets.db

Note that you can’t detach main (or temp) databases. If you attempt to do that, you’ll likely get this error:

sqlite> DETACH DATABASE main;
Error: cannot detach database main

Expressions

The ATTACH DATABASE syntax specifies that the file name you provide is actually an expression. You can provide a literal value or an expression.

The syntax for expressions is quite complex, and is outlined in the SQLite documentation if you’re interested.