SQLite
ATTACH Database
Query across multiple database files in one connection.
By EZ4Code Team
attachmulti-dbmigration
Code
-- Attach another database file
ATTACH DATABASE 'archive.db' AS archive;
-- List attached databases
PRAGMA database_list;
-- Query across databases
SELECT * FROM main.users
UNION ALL
SELECT * FROM archive.users WHERE archived_at < '2024-01-01';
-- Copy data between databases
INSERT INTO archive.users
SELECT * FROM main.users WHERE last_login < '2023-01-01';
DELETE FROM main.users WHERE last_login < '2023-01-01';
-- Detach when done
DETACH DATABASE archive;Explanation
ATTACH DATABASE adds another SQLite file to the current connection under an alias, allowing cross-database queries via the alias prefix. The main database is always called 'main', and attached databases are addressed by their alias. This is a common pattern for archiving old data without a full migration.
More SQLite Snippets
Create Table
Define tables with constraints and autoincrement keys.
Insert & Query
Insert rows and query with parameterized statements.
JOINs & Aggregates
Combine tables and aggregate grouped rows.
Indexes & EXPLAIN
Create indexes and inspect query plans.
Transactions & Savepoints
Wrap statements in atomic units with savepoints.
PRAGMA Statements
Configure SQLite behavior and inspect the database.