Detaching Databases
After using attached databases, detach them when no longer needed.
This keeps query context clear and reduces mistakes.
Core Concepts
flowchart TD
A[Attached DB in session] --> B[Use required queries]
B --> C[DETACH DATABASE alias]
C --> D[Verify with .databases]
| Command | Purpose |
|---|---|
DETACH DATABASE alias; | Remove one attached database from current connection |
.databases | Confirm remaining attachments |
Code Examples
-- Detach the database attached as archive.
DETACH DATABASE archive;
| Expected output |
|---|
| No result rows; command succeeds silently in most cases. |
-- Verify archive is no longer attached.
.databases
| Expected output |
|---|
archive no longer appears; main remains. |
SQLite-Specific Nuances
SQLite Nuance
Attach/detach scope is per connection. Closing sqlite3 ends all attachments automatically for that session.
Common Pitfalls / Best Practices
Pitfall
Trying to detach with wrong alias name (file name is not the alias unless you set it that way).
Best Practice
Run .databases before detaching so you can copy the exact alias.
Quick Challenge
Attach temp.db as tmp, verify it appears, then detach it and verify again.
View Solution
ATTACH DATABASE 'temp.db' AS tmp;
.databases
DETACH DATABASE tmp;
.databases
| Expected result |
|---|
tmp appears after attach, then disappears after detach. |