> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to update a column with values from another table using a dictionary

> Fill or correct a column with values looked up in another table by loading that table into a dictionary and calling dictGet in ALTER TABLE ... UPDATE.

[`ALTER TABLE ... UPDATE`](https://clickhouse.com/docs/reference/statements/alter/update) has no `FROM` or `JOIN` clause, and a subquery that refers to the row being updated is rejected with `Correlated subqueries in mutation update are not supported`. To set a column to values that are stored in another table, load that table into a [dictionary](https://clickhouse.com/docs/reference/statements/create/dictionary.md) and look the value up with [`dictGet`](https://clickhouse.com/docs/reference/functions/regular-functions/ext-dict-functions#dictGet) in the update expression.

## Example

The `orders` table has an empty `region` column. The region of each customer is in the `customers` table:

```sql theme={null}
CREATE TABLE orders
(
    order_id UInt64,
    customer_id String,
    region String
)
ENGINE = MergeTree
ORDER BY order_id;

CREATE TABLE customers
(
    customer_id String,
    region String
)
ENGINE = MergeTree
ORDER BY customer_id;

INSERT INTO orders (order_id, customer_id) VALUES
    (1, 'c-100'),
    (2, 'c-200'),
    (3, 'c-100'),
    (4, 'c-999');

INSERT INTO customers VALUES
    ('c-100', 'EMEA'),
    ('c-200', 'APAC');
```

Create a dictionary on top of `customers`, keyed by the column you join on:

```sql theme={null}
CREATE DICTIONARY customers_dict
(
    customer_id String,
    region String
)
PRIMARY KEY customer_id
SOURCE(CLICKHOUSE(TABLE 'customers'))
LAYOUT(COMPLEX_KEY_HASHED())
LIFETIME(0);
```

Update the column. `dictHas` restricts the update to the rows that have a match:

```sql theme={null}
ALTER TABLE orders
    UPDATE region = dictGet('customers_dict', 'region', customer_id)
    WHERE dictHas('customers_dict', customer_id)
SETTINGS mutations_sync = 1;

SELECT * FROM orders ORDER BY order_id;
```

```text theme={null}
   ┌─order_id─┬─customer_id─┬─region─┐
1. │        1 │ c-100       │ EMEA   │
2. │        2 │ c-200       │ APAC   │
3. │        3 │ c-100       │ EMEA   │
4. │        4 │ c-999       │        │
   └──────────┴─────────────┴────────┘
```

Drop the dictionary when the update has finished:

```sql theme={null}
DROP DICTIONARY customers_dict;
```

## Values that come from a join of several tables

A dictionary can load the result of a query instead of a table. Put the join into the `QUERY` of the source and name each column of the result after the dictionary attribute it fills. In this example the manager of an order is found through `customers` and `regions`:

```sql theme={null}
CREATE TABLE regions
(
    region String,
    manager String
)
ENGINE = MergeTree
ORDER BY region;

INSERT INTO regions VALUES
    ('EMEA', 'Dana'),
    ('APAC', 'Kim');

ALTER TABLE orders ADD COLUMN manager String;

CREATE DICTIONARY customer_managers_dict
(
    customer_id String,
    manager String
)
PRIMARY KEY customer_id
SOURCE(CLICKHOUSE(QUERY '
    SELECT c.customer_id AS customer_id, r.manager AS manager
    FROM default.customers AS c
    INNER JOIN default.regions AS r ON c.region = r.region
'))
LAYOUT(COMPLEX_KEY_HASHED())
LIFETIME(0);

ALTER TABLE orders
    UPDATE manager = dictGet('customer_managers_dict', 'manager', customer_id)
    WHERE dictHas('customer_managers_dict', customer_id)
SETTINGS mutations_sync = 1;

SELECT * FROM orders ORDER BY order_id;
```

```text theme={null}
   ┌─order_id─┬─customer_id─┬─region─┬─manager─┐
1. │        1 │ c-100       │ EMEA   │ Dana    │
2. │        2 │ c-200       │ APAC   │ Kim     │
3. │        3 │ c-100       │ EMEA   │ Dana    │
4. │        4 │ c-999       │        │         │
   └──────────┴─────────────┴────────┴─────────┘
```

One `ALTER TABLE ... UPDATE` can assign several columns, separated by commas, so that the affected parts are rewritten once.

## Things to know

* **Rows without a match.** For a key that is not in the dictionary, `dictGet` returns the default value of the attribute (an empty string or `0`). Without the `WHERE dictHas(...)` condition, the update overwrites the column in those rows with that default. To keep the current value instead, use [`dictGetOrDefault`](https://clickhouse.com/docs/reference/functions/regular-functions/ext-dict-functions#dictGetOrDefault): `UPDATE region = dictGetOrDefault('customers_dict', 'region', customer_id, region) WHERE 1`.
* **Key type and layout.** For a `String` key or a key of several columns, use [`COMPLEX_KEY_HASHED`](https://clickhouse.com/docs/reference/statements/create/dictionary/layouts/hashed#complex_key_hashed). A key of one column can be passed to `dictGet` as is; a key of several columns is passed as a tuple, for example `dictGet('prices_dict', 'price', (sku, currency))`. For a single `UInt64` key, use `HASHED`. See [passing keys to dictionary functions](https://clickhouse.com/docs/reference/functions/regular-functions/ext-dict-functions.md#passing-keys).
* **The update is a mutation.** It rewrites the data parts that contain matching rows in the background, and by default the statement returns before that work is done. [`mutations_sync = 1`](https://clickhouse.com/docs/reference/settings/session-settings/mutations#mutations_sync) makes the statement wait. Otherwise, follow the progress in [`system.mutations`](https://clickhouse.com/docs/reference/system-tables/mutations) and keep the dictionary until `is_done` is `1`.
* **The dictionary is a copy in memory.** It is loaded in full on first use, so the lookup table has to fit in memory; `bytes_allocated` in [`system.dictionaries`](https://clickhouse.com/docs/reference/system-tables/dictionaries) shows its size. With [`LIFETIME(0)`](https://clickhouse.com/docs/reference/statements/create/dictionary/lifetime) it is never refreshed: if you change the source table after the dictionary was loaded, run `SYSTEM RELOAD DICTIONARY customers_dict` before the update.
* **Replicated tables.** `dictGet` and `dictHas` are non-deterministic functions, because the content of a dictionary can differ between servers. On a `ReplicatedMergeTree` table the statement fails unless you allow it with [`allow_nondeterministic_mutations = 1`](https://clickhouse.com/docs/reference/settings/session-settings/allow-nondeterministic#allow_nondeterministic_mutations):

  ```text theme={null}
  Code: 36. DB::Exception: The source storage is replicated so ALTER UPDATE/ALTER DELETE statements must use only deterministic functions. Function 'dictGet' is non-deterministic. (BAD_ARGUMENTS)
  ```

  With the setting enabled, it is your responsibility that the dictionary exists on every replica and holds the same data there. Create it with `ON CLUSTER` or in a `Replicated` database, and do not change the source table until the mutation has finished.
* **ClickHouse Cloud.** A dictionary that reads from a ClickHouse table may need a `USER` and `PASSWORD` in its source. See the note in [ClickHouse dictionary source](https://clickhouse.com/docs/reference/statements/create/dictionary/sources/clickhouse.md).

## Alternatives

* A table with the [`Join`](https://clickhouse.com/docs/reference/engines/table-engines/special/join) engine and the [`joinGet`](https://clickhouse.com/docs/reference/functions/regular-functions/other-functions#joinGet) function work the same way: `UPDATE region = joinGet('default.customers_join', 'region', customer_id)`. Write the name of the `Join` table with its database. `joinGet` is non-deterministic as well, so the note about replicated tables applies.
* The lightweight [`UPDATE`](https://clickhouse.com/docs/reference/statements/update) statement accepts the same expression: `UPDATE orders SET region = dictGet('customers_dict', 'region', customer_id) WHERE dictHas('customers_dict', customer_id)`. It is a beta feature and needs the table settings described on its page.
