ttl.md 1.8 KB
Newer Older
1 2 3 4 5
---
toc_priority: 44
toc_title: TTL
---

A
++  
ana-uvarova 已提交
6
# Manipulations with Table TTL {#manipulations-with-table-ttl}
7

A
order  
ana-uvarova 已提交
8 9
## MODIFY TTL {#modify-ttl}

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

``` sql
A
++  
ana-uvarova 已提交
13
ALTER TABLE table_name MODIFY TTL ttl_expression;
14
```
A
Draft.  
ana-uvarova 已提交
15

A
ana-uvarova 已提交
16
## REMOVE TTL {#remove-ttl}
A
Draft.  
ana-uvarova 已提交
17

A
order  
ana-uvarova 已提交
18
Removes TTL-property from the specified column.
A
ana-uvarova 已提交
19

A
Draft.  
ana-uvarova 已提交
20 21 22
Syntax:

```sql
A
++  
ana-uvarova 已提交
23
ALTER TABLE table_name MODIFY column_name REMOVE TTL 
A
Draft.  
ana-uvarova 已提交
24 25
```

A
++  
ana-uvarova 已提交
26
**Example**
A
Draft.  
ana-uvarova 已提交
27

A
ana-uvarova 已提交
28
Requests and results:
A
order  
ana-uvarova 已提交
29

A
ana-uvarova 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
Firstly we should create a table to work with:

```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');
```

Trigger `TTL` works clearly with `OPTIMIZE` query. Make this to start the background cleaning using TTL:
A
Draft.  
ana-uvarova 已提交
50

A
++  
ana-uvarova 已提交
51
```sql
A
ana-uvarova 已提交
52 53
OPTIMIZE TABLE table_with_ttl FINAL;
SELECT * FROM table_with_ttl;
A
++  
ana-uvarova 已提交
54
```
A
ana-uvarova 已提交
55
As a result you see that the second line was deleted.
A
++  
ana-uvarova 已提交
56 57

```text
A
ana-uvarova 已提交
58 59
2020-12-11 12:44:57    1       username1
```
A
++  
ana-uvarova 已提交
60

A
ana-uvarova 已提交
61 62 63 64 65 66 67
```sql
ALTER TABLE table_with_ttl REMOVE TTL;
INSERT INTO table_with_ttl VALUES (now() - INTERVAL 4 MONTH, 2, 'username2');
OPTIMIZE TABLE table_with_ttl FINAL;
SELECT * FROM table_with_ttl;
```

A
ana-uvarova 已提交
68
Now TTL-property was removed and there is nothing to be deleted.
A
ana-uvarova 已提交
69 70

```text
A
ana-uvarova 已提交
71 72
|2020-12-11 12:44:57  |  1  |     username1|
|2020-08-11 12:44:57  |  2  |     username2|
A
++  
ana-uvarova 已提交
73
```
A
Draft.  
ana-uvarova 已提交
74

A
++  
ana-uvarova 已提交
75
### See Also
A
Draft.  
ana-uvarova 已提交
76

A
ana-uvarova 已提交
77 78
- More about the [TTL-expression](../../../sql-reference/statements/create/table#ttl-expression).
- Modify column [with TTL](../../../sql-reference/statements/alter/column#alter_modify-column).