[Yandex Cloud documentation](../../index.md) > [Yandex Data Transfer](../index.md) > [Tutorials](index.md) > Uploading data to data marts > MySQL® in ClickHouse®

# Loading data from MySQL® to a ClickHouse® data mart

# Asynchronous replication of data from Managed Service for MySQL® to Managed Service for ClickHouse® using Yandex Data Transfer


Data Transfer enables you to migrate your database from a MySQL® source cluster to ClickHouse®.

To transfer data:

1. [Set up your infrastructure](#prepare-infrastructure).
1. [Prepare the source cluster](#prepare-source).
1. [Prepare and activate your transfer](#prepare-transfer).
1. [Test the transfer](#verify-transfer).
1. [Query data in ClickHouse®](#working-with-data-ch).

If you no longer need the resources you created, [delete them](#clear-out).


## Getting started {#before-you-begin}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).

### Required paid resources {#paid-resources}

* Managed Service for MySQL® cluster, which includes computing resources allocated to hosts, storage and backup size (see [Managed Service for MySQL® pricing](../../managed-mysql/pricing.md)).
* Managed Service for ClickHouse® cluster, which includes the use of computing resources allocated to hosts, storage and backup size (see [Managed Service for ClickHouse® pricing](../../managed-clickhouse/pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* Each transfer, which includes the use of computing resources and the number of transferred data rows (see [Data Transfer pricing](../pricing.md)).


## Set up your infrastructure {#prepare-infrastructure}

{% list tabs group=instructions %}

- Manually {#manual}

    {% note info %}
    
    Public access to cluster hosts is required if you plan to connect to the cluster via the internet. This connection option is simpler and is recommended for the purposes of this guide. You can connect to non-public hosts as well but only from Yandex Cloud virtual machines located in the same cloud network as the cluster.
    
    {% endnote %}

    1. [Create a Managed Service for MySQL® source cluster](../../managed-mysql/operations/cluster-create.md) with your preferred configuration. Enable public access to the cluster during creation so you can connect to it from your local machine. Connections from within the Yandex Cloud network are enabled by default.

    1. [Create a target Managed Service for ClickHouse® cluster](../../managed-clickhouse/operations/cluster-create.md) with the following settings:

        * Number of ClickHouse® hosts: Minimum of 2 to enable replication within the cluster.
        * Database name: Must be identical to the database name in the source cluster.
        * Enable public access to the cluster during creation so you can connect to it from your local machine. Connections from within the Yandex Cloud network are enabled by default.

    
    1. If using security groups, configure them to allow internet access to your clusters:

        * [Managed Service for MySQL®](../../managed-mysql/operations/connect/index.md#configuring-security-groups).
        * [Managed Service for ClickHouse®](../../managed-clickhouse/operations/connect/index.md#configuring-security-groups).


- Terraform {#tf}

    1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
    1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
    1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
    1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

    1. Download the [data-transfer-mmy-mch.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-from-mysql-to-clickhouse/blob/main/data-transfer-mmy-mch.tf) configuration file to your current working directory.

        This file describes:

        * [Network](../../vpc/concepts/network.md#network).
        * [Subnets](../../vpc/concepts/network.md#subnet).
        * [Security group](../../vpc/concepts/security-groups.md) and the rule required for connecting to the Managed Service for MySQL® cluster.
        * Managed Service for MySQL® source cluster.
        * Managed Service for ClickHouse® target cluster.
        * Source endpoint.
        * Target endpoint.
        * Transfer.

    1. In the `data-transfer-mmy-mch.tf` file, specify the following:

        * Managed Service for MySQL® source cluster parameters to use for the [source endpoint](../operations/endpoint/target/mysql.md#managed-service):

            * `source_mysql_version`: MySQL® version.
            * `source_db_name`: MySQL® database name.
            * `source_user` and `source_password`: Database owner username and password.

        * Managed Service for ClickHouse® target cluster parameters to use for the [target endpoint](../operations/endpoint/target/clickhouse.md#managed-service):

            * `target_db_name`: ClickHouse® database name.
            * `target_user` and `target_password`: Database owner username and password.

    1. Validate your Terraform configuration files using this command:

        ```bash
        terraform validate
        ```

        Terraform will display any configuration errors detected in your files.

    1. Create the required infrastructure:

        1. Run this command to view the planned changes:
        
           ```bash
           terraform plan
           ```
        
           If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
        
        1. If everything looks correct, apply the changes:
           1. Run this command:
        
              ```bash
              terraform apply
              ```
        
           1. Confirm updating the resources.
           1. Wait for the operation to complete.

        All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

{% endlist %}

## Prepare the source cluster {#prepare-source}

1. If you created the infrastructure manually, [set up your source cluster](../operations/prepare.md#source-my).

1. [Connect to the Managed Service for MySQL® source cluster](../../managed-mysql/operations/connect/index.md).

1. Populate the database with test data.

    1. Create a table named `x_tab`:

    ```sql
    CREATE TABLE x_tab
    (
        id INT,
        name TEXT,
        PRIMARY KEY (id)
    );
    ```

    1. Populate the table with data:

    ```sql
    INSERT INTO x_tab (id, name) VALUES
        (40, 'User1'),
        (41, 'User2'),
        (42, 'User3'),
        (43, 'User4'),
        (44, 'User5');
    ```

## Prepare and activate your transfer {#prepare-transfer}

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Create a source endpoint](../operations/endpoint/index.md#create):

        * **Database type**: `MySQL®`.
        * **Endpoint parameters** → **Connection settings**: `Managed Service for MySQL cluster`.

            Select your source cluster from the list and specify its connection settings.

    1. [Create a target endpoint](../operations/endpoint/index.md#create):

        * **Database type**: `ClickHouse`.
        * **Endpoint parameters** → **Connection settings**: `Managed cluster`.

            Select your target cluster from the list and specify its connection settings.

    1. [Create a transfer](../operations/transfer.md#create) of the **_Snapshot and replication_**-type that will use the endpoints you created.
    1. [Activate](../operations/transfer.md#activate) the transfer.

- Terraform {#tf}

    1. In the `data-transfer-mmy-mch.tf` file, set the `transfer_enabled` variable to `1`.

    1. Make sure the Terraform configuration files are correct using this command:

        ```bash
        terraform validate
        ```

        Terraform will display any configuration errors detected in your files.

    1. Create the required infrastructure:

        1. Run this command to view the planned changes:
        
           ```bash
           terraform plan
           ```
        
           If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
        
        1. If everything looks correct, apply the changes:
           1. Run this command:
        
              ```bash
              terraform apply
              ```
        
           1. Confirm updating the resources.
           1. Wait for the operation to complete.

        The transfer will be activated automatically upon creation.

{% endlist %}

## Test the transfer {#verify-transfer}

1. Wait for the transfer status to change to **Replicating**.

1. Make sure the data from the Managed Service for MySQL® source cluster has been transferred to the Managed Service for ClickHouse® database:

    1. [Connect to the cluster](../../managed-clickhouse/operations/connect/clients.md#clickhouse-client) using `clickhouse-client`.

    1. Run this query:

        ```sql
        SELECT * FROM <ClickHouse®_database_name>.x_tab
        ```

        Result:

        ```text
        ┌─id─┬─name──┬─__data_transfer_commit_time─┬─__data_transfer_delete_time─┐
        │ 40 │ User1 │         1661952756538347180 │                           0 │
        │ 41 │ User2 │         1661952756538347180 │                           0 │
        │ 42 │ User3 │         1661952756538347180 │                           0 │
        │ 43 │ User4 │         1661952756538347180 │                           0 │
        │ 44 │ User5 │         1661952756538347180 │                           0 │
        └────┴───────┴─────────────────────────────┴─────────────────────────────┘
        ```

        The table also contains the following [timestamp columns](#working-with-data-ch): `__data_transfer_commit_time` and `__data_transfer_delete_time`.

1. In the source MySQL® table `x_tab`, delete the row with `id` = `41` and update the row with `id` = `42`:

    1. [Connect to the Managed Service for MySQL® source cluster](../../managed-mysql/operations/connect/index.md).

    1. Run the following queries:

        ```sql
        DELETE FROM x_tab WHERE id = 41;
        UPDATE x_tab SET name = 'Key3' WHERE id = 42;
        ```

1. Make sure the changes have been applied to the `x_tab` table on the ClickHouse® target:

    ```sql
    SELECT * FROM <ClickHouse®_database_name>.x_tab WHERE id in (41,42);
    ```

    Result:

    ```text
    ┌─id─┬─name──┬─__data_transfer_commit_time─┬─__data_transfer_delete_time─┐
    │ 41 │ User2 │         1661952756538347180 │                           0 │
    │ 42 │ User3 │         1661952756538347180 │                           0 │
    └────┴───────┴─────────────────────────────┴─────────────────────────────┘
    ┌─id─┬─name─┬─__data_transfer_commit_time─┬─__data_transfer_delete_time─┐
    │ 41 │ ᴺᵁᴸᴸ │         1661953256000000000 │         1661953256000000000 │
    └────┴──────┴─────────────────────────────┴─────────────────────────────┘
    ┌─id─┬─name─┬─__data_transfer_commit_time─┬─__data_transfer_delete_time─┐
    │ 42 │ Key3 │         1661953280000000000 │                           0 │
    └────┴──────┴─────────────────────────────┴─────────────────────────────┘
    ```

## Query data in ClickHouse® {#working-with-data-ch}

For table recovery, ClickHouse® targets with [replication](../../managed-clickhouse/concepts/replication.md) use the [ReplicatedReplacingMergeTree](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/replication) and [ReplacingMergeTree](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/replacingmergetree) engines. The following columns are automatically added to each table:

* `__data_transfer_commit_time`: Time the row was updated to this value, in `TIMESTAMP` format.
* `__data_transfer_delete_time`: Time the row was deleted from the source, in `TIMESTAMP` format. A value of `0` indicates that the row is still active.

    The `__data_transfer_commit_time` column is essential for the ReplicatedReplacedMergeTree engine. If a record is deleted or updated, a new row gets inserted with a value in this column. Querying by the primary key alone returns several records with different `__data_transfer_commit_time` values.

The source data can be added or deleted while the transfer is in **Replicating** status. For standard SQL command behavior, where the primary key returns a single record, add filtering by the `__data_transfer_delete_time` column when querying tables transferred to ClickHouse®. For example, to query the `x_tab` table, use the following syntax:

```sql
SELECT * FROM <ClickHouse®_database_name>.x_tab FINAL
WHERE __data_transfer_delete_time = 0;
```

To simplify the `SELECT` queries, create a view filtering rows by `__data_transfer_delete_time`. Use this view for all your queries. For example, to query the `x_tab` table, use the following syntax:

```sql
CREATE VIEW x_tab_view AS SELECT * FROM <ClickHouse®_database_name>.x_tab FINAL
WHERE __data_transfer_delete_time == 0;
```

## Delete the resources you created {#clear-out}

{% note info %}

Before deleting the created resources, [deactivate the transfer](../operations/transfer.md#deactivate).

{% endnote %}

To minimize resource consumption, delete the resources you no longer need:

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Delete the transfer](../operations/transfer.md#delete-transfer).
    1. [Delete the source and target endpoints](../operations/endpoint/index.md#delete).
    1. [Delete the Managed Service for MySQL® cluster](../../managed-mysql/operations/cluster-delete.md).
    1. [Delete the Managed Service for ClickHouse® cluster](../../managed-clickhouse/operations/cluster-delete.md).

- Terraform {#tf}

    1. In the terminal window, go to the directory containing the infrastructure plan.
    
        {% note warning %}
    
        Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
    
        {% endnote %}
    
    1. Delete resources:
    
        1. Run this command:
    
            ```bash
            terraform destroy
            ```
    
        1. Confirm deleting the resources and wait for the operation to complete.
    
        All the resources described in the Terraform manifests will be deleted.

{% endlist %}

_ClickHouse® is a registered trademark of [ClickHouse, Inc](https://clickhouse.com)._