> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-fbfa8bee.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# How to use the exchange command to switch tables

> How to use the exchange command to switch tables

{frontMatter.description}

***

<h2 id="question">
  Question
</h2>

How do I use the [`EXCHANGE`](/reference/statements/exchange) command to switch table names?

<h2 id="answer">
  Answer
</h2>

The `EXCHANGE` command is useful when you need to switch a current table with another table that is temporary where possibly Primary Keys or other settings were updated.
This happens atomically vs with the `RENAME` command.
It is also useful when you have Materialized Views triggering on a source table and are trying to avoid rebuilding the view.

Below is a simple example on how it works and how to test:

* Create sample database

```sql theme={null}
create database db1;
```

* Create example table

```sql theme={null}
create table db1.table1_exchange
(
 id Int32,
 string_field String
)
engine = MergeTree()
order by id;
```

* Insert sample row

```sql theme={null}
insert into db1.table1_exchange
values
(1, 'a');
```

* Create example temporary table that will be exchanged

```sql theme={null}
create table db1.table1_exchange_temp
(
 id Int32,
 string_field String
)
engine = MergeTree()
order by id;
```

* Insert sample row into the temporary table

```sql theme={null}
insert into db1.table1_exchange_temp
values
(2, 'b');
```

* Run the `EXCHANGE` command to switch the tables

```sql theme={null}
exchange tables db1.table1_exchange and db1.table1_exchange_temp;
```

* Test that the tables are now exchanged and show the rows are switched

```sql theme={null}
select * from db1.table1_exchange;
```

```text theme={null}
┌─id─┬─string_field─┐
│  2 │ b            │
└────┴──────────────┘

1 row in set. Elapsed: 0.002 sec. 
```
