Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOCSUP-3122: Document two expressions ALTER #17059

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/en/sql-reference/statements/alter/column.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ The following actions are supported:
- [CLEAR COLUMN](#alter_clear-column) — Resets column values.
- [COMMENT COLUMN](#alter_comment-column) — Adds a text comment to the column.
- [MODIFY COLUMN](#alter_modify-column) — Changes column’s type, default expression and TTL.
- [MODIFY COLUMN REMOVE](#modify-remove) — Removes one of the column properties.

These actions are described in detail below.

Expand Down Expand Up @@ -136,6 +137,26 @@ If there is a failure during one of the successive stages, data can be restored

The `ALTER` query for changing columns is replicated. The instructions are saved in ZooKeeper, then each replica applies them. All `ALTER` queries are run in the same order. The query waits for the appropriate actions to be completed on the other replicas. However, a query to change columns in a replicated table can be interrupted, and all actions will be performed asynchronously.

## MODIFY COLUMN REMOVE {#modify-remove}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missed anchor here

Removes one of the column properties: `DEFAULT`, `ALIAS`, `MATERIALIZED`, `CODEC`, `COMMENT`, `TTL`.

Syntax:

```sql
ALTER TABLE table_name MODIFY column_name REMOVE property;
```

**Example**

```sql
ALTER TABLE table_with_ttl MODIFY COLUMN column_ttl REMOVE TTL;
```

## See Also

- [REMOVE TTL](ttl.md).

## Limitations {#alter-query-limitations}

The `ALTER` query lets you create and delete separate elements (columns) in nested data structures, but not whole nested data structures. To add a nested data structure, you can add columns with a name like `name.nested_name` and the type `Array(T)`. A nested data structure is equivalent to multiple array columns with a name that has the same prefix before the dot.
Expand Down
77 changes: 75 additions & 2 deletions docs/en/sql-reference/statements/alter/ttl.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,83 @@ toc_priority: 44
toc_title: TTL
---

### Manipulations with Table TTL {#manipulations-with-table-ttl}
# Manipulations with Table TTL {#manipulations-with-table-ttl}

## MODIFY TTL {#modify-ttl}

You can change [table TTL](../../../engines/table-engines/mergetree-family/mergetree.md#mergetree-table-ttl) with a request of the following form:

``` sql
ALTER TABLE table-name MODIFY TTL ttl-expression
ALTER TABLE table_name MODIFY TTL ttl_expression;
```

## REMOVE TTL {#remove-ttl}

Copy link
Contributor

@olgarev olgarev Dec 18, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"#" missed in anchor. Should be {#remove-ttl}

TTL-property can be removed from table with the following query:

```sql
ALTER TABLE table_name REMOVE TTL
```

**Example**

Consider the table with table `TTL`:

```sql
CREATE TABLE table_with_ttl
(
event_time DateTime,
UserID UInt64,
Comment String
)
ENGINE MergeTree()
ORDER BY tuple()
TTL event_time + INTERVAL 3 MONTH;
SETTINGS min_bytes_for_wide_part = 0;

INSERT INTO table_with_ttl VALUES (now(), 1, 'username1');

INSERT INTO table_with_ttl VALUES (now() - INTERVAL 4 MONTH, 2, 'username2');
```

Run `OPTIMIZE` to force `TTL` cleanup:

```sql
OPTIMIZE TABLE table_with_ttl FINAL;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No table definition and now info about data. How reader can guess it?

SELECT * FROM table_with_ttl FORMAT PrettyCompact;
```
Second row was deleted from table.

```text
┌─────────event_time────┬──UserID─┬─────Comment──┐
│ 2020-12-11 12:44:57 │ 1 │ username1 │
└───────────────────────┴─────────┴──────────────┘
```

Now remove table `TTL` with the following query:

```sql
ALTER TABLE table_with_ttl REMOVE TTL;
```

Re-insert the deleted row and force the `TTL` cleanup again with `OPTIMIZE`:

```sql
INSERT INTO table_with_ttl VALUES (now() - INTERVAL 4 MONTH, 2, 'username2');
OPTIMIZE TABLE table_with_ttl FINAL;
SELECT * FROM table_with_ttl FORMAT PrettyCompact;
```

The `TTL` is no longer there, so the second row is not deleted:

```text
┌─────────event_time────┬──UserID─┬─────Comment──┐
│ 2020-12-11 12:44:57 │ 1 │ username1 │
│ 2020-08-11 12:44:57 │ 2 │ username2 │
└───────────────────────┴─────────┴──────────────┘
```

### See Also

- More about the [TTL-expression](../../../sql-reference/statements/create/table#ttl-expression).
- Modify column [with TTL](../../../sql-reference/statements/alter/column#alter_modify-column).
25 changes: 24 additions & 1 deletion docs/ru/sql-reference/statements/alter/column.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ toc_title: "\u041c\u0430\u043d\u0438\u043f\u0443\u043b\u044f\u0446\u0438\u0438\u
- [CLEAR COLUMN](#alter_clear-column) — сбрасывает все значения в столбце для заданной партиции;
- [COMMENT COLUMN](#alter_comment-column) — добавляет комментарий к столбцу;
- [MODIFY COLUMN](#alter_modify-column) — изменяет тип столбца, выражение для значения по умолчанию и TTL.
- [MODIFY COLUMN REMOVE](#modify-remove) — удаляет какое-либо из свойств столбца.

Подробное описание для каждого действия приведено ниже.

Expand Down Expand Up @@ -125,6 +126,28 @@ ALTER TABLE visits MODIFY COLUMN browser Array(String)

Запрос `ALTER` на изменение столбцов реплицируется. Соответствующие инструкции сохраняются в ZooKeeper, и затем каждая реплика их применяет. Все запросы `ALTER` выполняются в одном и том же порядке. Запрос ждёт выполнения соответствующих действий на всех репликах. Но при этом, запрос на изменение столбцов в реплицируемой таблице можно прервать, и все действия будут осуществлены асинхронно.

## MODIFY COLUMN REMOVE {#modify-remove}

Удаляет какое-либо из свойств столбца: `DEFAULT`, `ALIAS`, `MATERIALIZED`, `CODEC`, `COMMENT`, `TTL`.

Синтаксис:

```sql
ALTER TABLE table_name MODIFY column_name REMOVE property;
```

**Пример**

Удаление свойства TTL:

```sql
ALTER TABLE table_with_ttl MODIFY COLUMN column_ttl REMOVE TTL;
```

## Смотрите также

- [REMOVE TTL](ttl.md).

## Ограничения запроса ALTER {#ogranicheniia-zaprosa-alter}

Запрос `ALTER` позволяет создавать и удалять отдельные элементы (столбцы) вложенных структур данных, но не вложенные структуры данных целиком. Для добавления вложенной структуры данных, вы можете добавить столбцы с именем вида `name.nested_name` и типом `Array(T)` - вложенная структура данных полностью эквивалентна нескольким столбцам-массивам с именем, имеющим одинаковый префикс до точки.
Expand All @@ -137,4 +160,4 @@ ALTER TABLE visits MODIFY COLUMN browser Array(String)

Для таблиц, которые не хранят данные самостоятельно (типа [Merge](../../../sql-reference/statements/alter/index.md) и [Distributed](../../../sql-reference/statements/alter/index.md)), `ALTER` всего лишь меняет структуру таблицы, но не меняет структуру подчинённых таблиц. Для примера, при ALTER-е таблицы типа `Distributed`, вам также потребуется выполнить запрос `ALTER` для таблиц на всех удалённых серверах.

[Оригинальная статья](https://clickhouse.tech/docs/ru/query_language/alter/column/) <!--hide-->
[Оригинальная статья](https://clickhouse.tech/docs/ru/query_language/alter/column/) <!--hide-->
74 changes: 73 additions & 1 deletion docs/ru/sql-reference/statements/alter/ttl.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,82 @@ toc_title: TTL

# Манипуляции с TTL таблицы {#manipuliatsii-s-ttl-tablitsy}

## MODIFY TTL {#modify-ttl}

Вы можете изменить [TTL для таблицы](../../../engines/table-engines/mergetree-family/mergetree.md#mergetree-column-ttl) запросом следующего вида:

``` sql
ALTER TABLE table-name MODIFY TTL ttl-expression
```

[Оригинальная статья](https://clickhouse.tech/docs/ru/query_language/alter/ttl/) <!--hide-->
## REMOVE TTL {#remove-ttl}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"#" missed in anchor. Should be {#remove-ttl}

Удалить табличный TTL можно запросом следующего вида:

```sql
ALTER TABLE table_name REMOVE TTL
```

**Пример**

Создадим таблицу с табличным `TTL` и заполним её данными:

```sql
CREATE TABLE table_with_ttl
(
event_time DateTime,
UserID UInt64,
Comment String
)
ENGINE MergeTree()
ORDER BY tuple()
TTL event_time + INTERVAL 3 MONTH;
SETTINGS min_bytes_for_wide_part = 0;

INSERT INTO table_with_ttl VALUES (now(), 1, 'username1');

INSERT INTO table_with_ttl VALUES (now() - INTERVAL 4 MONTH, 2, 'username2');
```

Выполним `OPTIMIZE` для принудительной очистки по `TTL`:

```sql
OPTIMIZE TABLE table_with_ttl FINAL;
SELECT * FROM table_with_ttl;
```
В результате видно, что вторая строка удалена.

```text
┌─────────event_time────┬──UserID─┬─────Comment──┐
│ 2020-12-11 12:44:57 │ 1 │ username1 │
└───────────────────────┴─────────┴──────────────┘
```

Удаляем табличный `TTL`:

```sql
ALTER TABLE table_with_ttl REMOVE TTL;
```

Заново вставляем удаленную строку и снова принудительно запускаем очистку по `TTL` с помощью `OPTIMIZE`:

```sql
INSERT INTO table_with_ttl VALUES (now() - INTERVAL 4 MONTH, 2, 'username2');
OPTIMIZE TABLE table_with_ttl FINAL;
SELECT * FROM table_with_ttl;
```

`TTL` больше нет, поэтому данные не удаляются:

```text
┌─────────event_time────┬──UserID─┬─────Comment──┐
│ 2020-12-11 12:44:57 │ 1 │ username1 │
│ 2020-08-11 12:44:57 │ 2 │ username2 │
└───────────────────────┴─────────┴──────────────┘
```

### Смотрите также

- Подробнее о [свойстве TTL](../../../engines/table-engines/mergetree-family/mergetree#table_engine-mergetree-ttl).

[Оригинальная статья](https://clickhouse.tech/docs/ru/query_language/alter/ttl/) <!--hide-->