---
title: "ATTACH and DETACH"
description: "ATTACH and DETACH let a database session connect to (or disconnect from) additional database files at runtime, enabling cross-database queries without a separate connection."
canonical: "https://motherduck.com/glossary/attach-and-detach/"
related:
  - title: "ATTACH/DETACH | MotherDuck Docs"
    url: "https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/attach-detach/"
  - title: "DuckLake Architecture Deep Dive: Catalog, Storage, Compute | MotherDuck"
    url: "https://motherduck.com/videos/ducklake-architecture-deep-dive/"
  - title: "DETACH | MotherDuck Docs"
    url: "https://motherduck.com/docs/sql-reference/motherduck-sql-reference/detach/"
---

# ATTACH and DETACH

> ATTACH and DETACH let a database session connect to (or disconnect from) additional database files at runtime, enabling cross-database queries without a separate connection.

## Overview
In embedded/single-file databases like DuckDB and SQLite, `ATTACH` lets an active session bring in another database file under an alias, so you can query or join across multiple database files as if they were schemas in one database. `DETACH` removes an attached database from the session.

```sql
ATTACH 'warehouse.db' AS warehouse;
ATTACH 'archive.db' AS archive (READ_ONLY);

SELECT * FROM warehouse.main.orders
UNION ALL
SELECT * FROM archive.main.orders;

DETACH archive;
```

Once attached, tables are referenced as `alias.schema.table` (or just `alias.table`, since `main` is the default schema), and DDL/DML can target the attached database directly.

## DuckDB specifics
DuckDB's `ATTACH 'path' AS alias (OPTIONS...)` supports a `READ_ONLY` option for safe concurrent access to a file another process might also be reading, a `TYPE` option to attach non-DuckDB databases (SQLite and PostgreSQL, via their respective extensions), and options like `ENCRYPTION_KEY` for encrypted databases. `USE alias` switches the session's default database context, so subsequent unqualified table names resolve against that database:

```sql
ATTACH 'sales.db' AS sales;
USE sales;
SELECT * FROM orders;  -- resolves to sales.main.orders
```

A DuckDB in-memory session can attach any number of on-disk databases at once, which is the basis for DuckDB's common use as a cross-database query engine — joining data that physically lives in separate DuckDB files (or even separate database systems, like an attached PostgreSQL database) in a single query. `DETACH alias` releases the attachment; you cannot detach the database currently selected as the default via `USE`.