Skip to main content

Attaching Databases

ATTACH DATABASE lets one SQLite session work with multiple database files at once.

This is useful for migration tasks, comparisons, and staged imports.

Core Concepts

flowchart LR
A[(main.db)] --> C[SQLite session]
B[(archive.db)] --> C
C --> D[Use main.table and archive.table]
ConceptExample
Main database aliasmain
Attached aliasarchive
Qualified object namearchive.customers

Code Examples

-- Attach another database file with alias archive.
ATTACH DATABASE 'archive.db' AS archive;

-- Show all attached databases.
.databases
Expected output
.databases shows at least main and archive.
-- Query from attached database using schema-qualified name.
SELECT name
FROM archive.sqlite_schema
WHERE type = 'table';
name
e.g. table names from archive.db

SQLite-Specific Nuances

SQLite Nuance

SQLite supports multiple attached database files in one connection, each with its own schema name.

Qualified naming (alias.table) avoids ambiguity.

Common Pitfalls / Best Practices

Pitfall

Forgetting schema qualifiers when object names overlap across main and attached databases.

Best Practice

Use short, meaningful aliases such as src, dst, archive, or staging.

Quick Challenge

Attach legacy.db as legacy and list its table names via legacy.sqlite_schema.

View Solution
ATTACH DATABASE 'legacy.db' AS legacy;
SELECT name
FROM legacy.sqlite_schema
WHERE type = 'table';
name
table names from legacy.db