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

# 用于故障排查的实用查询

> 一组用于排查 ClickHouse 故障的实用查询，包括监控表大小、长时间运行的查询以及错误。

{frontMatter.description}

<div id="useful-queries-for-troubleshooting">
  ## 用于故障排查的实用查询
</div>

以下列出一些实用查询，不分先后，可用于排查 ClickHouse 故障并了解当前发生的情况。

我们还提供了一篇很棒的博客，介绍了一些[监控 ClickHouse 的关键查询](https://clickhouse.com/blog/monitoring-troubleshooting-select-queries-clickhouse)。

<div id="view-which-settings-have-been-changed-from-the-default">
  ## 查看哪些设置已偏离默认值
</div>

```sql theme={null}
SELECT
    name,
    value
FROM system.settings
WHERE changed
```

<div id="get-the-size-of-all-your-tables">
  ## 查看所有表的大小
</div>

```sql theme={null}
SELECT table,
    formatReadableSize(sum(bytes)) as size
    FROM system.parts
    WHERE active
GROUP BY table
```

返回结果如下：

```response theme={null}
┌─table───────────┬─size──────┐
│ stat            │ 38.89 MiB │
│ customers       │ 525.00 B  │
│ my_sparse_table │ 40.73 MiB │
│ crypto_prices   │ 32.18 MiB │
│ hackernews      │ 6.23 GiB  │
└─────────────────┴───────────┘
```

<div id="row-count-and-average-day-size-of-your-table">
  ## 表的行数和日均大小
</div>

```sql theme={null}
SELECT
    table,
    formatReadableSize(size) AS size,
    rows,
    days,
    formatReadableSize(avgDaySize) AS avgDaySize
FROM
(
    SELECT
        table,
        sum(bytes) AS size,
        sum(rows) AS rows,
        min(min_date) AS min_date,
        max(max_date) AS max_date,
        max_date - min_date AS days,
        size / (max_date - min_date) AS avgDaySize
    FROM system.parts
    WHERE active
    GROUP BY table
    ORDER BY rows DESC
)
```

<div id="compression-columns-percentage-as-well-as-the-size-of-primary-index-in-memory">
  ## 各列的压缩率以及内存中主索引的大小
</div>

你可以按列查看数据的压缩率。此查询还会返回主索引在内存中的大小——这一点很重要，因为主索引必须能放入内存。

```sql theme={null}
SELECT
    parts.*,
    columns.compressed_size,
    columns.uncompressed_size,
    columns.compression_ratio,
    columns.compression_percentage
FROM
(
    SELECT
        table,
        formatReadableSize(sum(data_uncompressed_bytes)) AS uncompressed_size,
        formatReadableSize(sum(data_compressed_bytes)) AS compressed_size,
        round(sum(data_compressed_bytes) / sum(data_uncompressed_bytes), 3) AS compression_ratio,
        round(100 - ((sum(data_compressed_bytes) * 100) / sum(data_uncompressed_bytes)), 3) AS compression_percentage
    FROM system.columns
    GROUP BY table
) AS columns
RIGHT JOIN
(
    SELECT
        table,
        sum(rows) AS rows,
        max(modification_time) AS latest_modification,
        formatReadableSize(sum(bytes)) AS disk_size,
        formatReadableSize(sum(primary_key_bytes_in_memory)) AS primary_keys_size,
        any(engine) AS engine,
        sum(bytes) AS bytes_size
    FROM system.parts
    WHERE active
    GROUP BY
        database,
        table
) AS parts ON columns.table = parts.table
ORDER BY parts.bytes_size DESC
```

<div id="number-of-queries-sent-by-client-in-the-last-10-minutes">
  ## 最近 10 分钟内客户端发送的查询数
</div>

你可以根据需要在 `toIntervalMinute(10)` 函数中调大或调小时间间隔：

```sql theme={null}
SELECT
    client_name,
    count(),
    query_kind,
    toStartOfMinute(event_time) AS event_time_m
FROM system.query_log
WHERE (type = 'QueryStart') AND (event_time > (now() - toIntervalMinute(10)))
GROUP BY
    event_time_m,
    client_name,
    query_kind
ORDER BY
    event_time_m DESC,
    count() ASC
```

<div id="number-of-parts-in-each-partition">
  ## 各分区中的 parts 数量
</div>

```sql theme={null}
SELECT
    concat(database, '.', table),
    partition_id,
    count()
FROM system.parts
WHERE active
GROUP BY
    database,
    table,
    partition_id
```

<div id="finding-long-running-queries">
  ## 查找运行时间较长的查询
</div>

这有助于找出卡住不动的查询：

```sql theme={null}
SELECT
    elapsed,
    initial_user,
    client_name,
    hostname(),
    query_id,
    query
FROM clusterAllReplicas(default, system.processes)
ORDER BY elapsed DESC
```

使用运行最慢的查询的 query id，我们可以获取有助于调试的堆栈跟踪。

```
SET allow_introspection_functions=1;

SELECT
    arrayStringConcat(
        arrayMap(
            x,
            y -> concat(x, ': ', y),
            arrayMap(x -> addressToLine(x), trace),
            arrayMap(x -> demangle(addressToSymbol(x)), trace)
        ),
        '\n'
    ) as trace
FROM
    system.stack_trace
WHERE
    query_id = '0bb6e88b-9b9a-4ffc-b612-5746c859e360';
```

<div id="view-the-most-recent-errors">
  ## 查看最新错误
</div>

```
SELECT *
FROM system.errors
ORDER BY last_error_time DESC
```

响应如下：

```response theme={null}
┌─name──────────────────┬─code─┬─value─┬─────last_error_time─┬─last_error_message──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─last_error_trace─┬─remote─┐
│ UNKNOWN_TABLE         │   60 │     3 │ 2023-03-14 01:02:35 │ Table system.stack_trace doesn't exist                                                                                                              │ []               │      0 │
│ BAD_GET               │  170 │     1 │ 2023-03-14 00:58:55 │ Requested cluster 'default' not found                                                                                                               │ []               │      0 │
│ UNKNOWN_IDENTIFIER    │   47 │     1 │ 2023-03-14 00:49:12 │ Missing columns: 'parts.table' 'table' while processing query: 'table = parts.table', required columns: 'table' 'parts.table' 'table' 'parts.table' │ []               │      0 │
│ NO_ELEMENTS_IN_CONFIG │  139 │     2 │ 2023-03-14 00:42:11 │ Certificate file is not set.                                                                                                                        │ []               │      0 │
└───────────────────────┴──────┴───────┴─────────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴──────────────────┴────────┘
```

<div id="top-10-queries-that-are-using-the-most-cpu-and-memory">
  ## 占用 CPU 和内存最多的前 10 个查询
</div>

```sql theme={null}
SELECT
    type,
    event_time,
    initial_query_id,
    formatReadableSize(memory_usage) AS memory,
    `ProfileEvents.Values`[indexOf(`ProfileEvents.Names`, 'UserTimeMicroseconds')] AS userCPU,
    `ProfileEvents.Values`[indexOf(`ProfileEvents.Names`, 'SystemTimeMicroseconds')] AS systemCPU,
    normalizedQueryHash(query) AS normalized_query_hash
FROM system.query_log
ORDER BY memory_usage DESC
LIMIT 10
```

<Note>
  单个查询可能会以具有不同 `query_id` 值的多行形式记录——分布式次级查询和内部视图步骤的 `is_initial_query = 0`。请过滤 `is_initial_query = 1` (或 `query_id = initial_query_id`) ，以查看查询提交时的原始形式，并注意 ClickHouse 分配的内部 `query_id` 值可能会包含类似 `queryView...` 的标签。有关详细信息，请参阅 [`query_log` 参考](/zh/reference/system-tables/query_log)。
</Note>

<div id="how-much-disk-space-are-my-projection-using">
  ## 我的投影占用了多少磁盘空间
</div>

```sql theme={null}
SELECT
    name,
    parent_name,
    formatReadableSize(bytes_on_disk) AS bytes,
    formatReadableSize(parent_bytes_on_disk) AS parent_bytes,
    bytes_on_disk / parent_bytes_on_disk AS ratio
FROM system.projection_parts
```

<div id="show-disk-storage-number-of-parts-number-of-rows-in-systemparts-and-marks-across-databases">
  ## 显示各数据库的磁盘存储、parts 数量、system.parts 中的行数和标记数
</div>

```sql theme={null}
SELECT
    database,
    table,
    partition,
    count() AS parts,
    formatReadableSize(sum(bytes_on_disk)) AS bytes_on_disk,
    formatReadableQuantity(sum(rows)) AS rows,
    sum(marks) AS marks
FROM system.parts
WHERE (database != 'system') AND active
GROUP BY
    database,
    table,
    partition
ORDER BY database ASC
```

<div id="list-details-of-recently-written-new-parts">
  ## 列出最近新写入的 parts 详细信息
</div>

这些详细信息包括其创建时间、大小、行数等：

```sql theme={null}
SELECT
    modification_time,
    rows,
    formatReadableSize(bytes_on_disk),
    *
FROM clusterAllReplicas(default, system.parts)
WHERE (database = 'default') AND active AND (level = 0)
ORDER BY modification_time DESC
LIMIT 100
```

<div id="cluster-wide-monitoring-queries">
  ## 集群级监控查询
</div>

以下查询可用于监控 ClickHouse 集群。它们使用 `clusterAllReplicas()` 汇总所有节点上的数据。

<Note>
  这些查询默认你的集群名称为 `default`。如果集群名称不同，请将 `'default'` 和 `default` 替换为你的实际集群名称。
</Note>

<div id="avg-new-parts-per-minute-and-second">
  ### 最近一小时内平均每分钟和每秒创建的新 parts
</div>

```sql theme={null}
WITH
    PER_MINUTE AS
    (
    SELECT
        toStartOfInterval(modification_time, toIntervalMinute(1)) AS t,
        count() AS new_part_count
    FROM
        clusterAllReplicas(default, merge(system, '^parts'))
    WHERE
        (database = 'default') AND
        (table = 'your_table') AND
        (active = true) AND
        (level = 0) AND
        (modification_time >= (now() - toIntervalHour(1)))
    GROUP BY
        t
    ORDER BY
        t ASC
    SETTINGS skip_unavailable_shards = 1
    )
SELECT
    AVG(new_part_count) AS new_parts_per_minute,
    new_parts_per_minute / 60 AS new_parts_per_second
FROM
    PER_MINUTE
```

将 `'your_table'` 替换为要监控的实际表名。

<div id="cpu-and-memory-intensive-queries-cluster-wide">
  ### CPU 和内存密集型查询 (集群级)
</div>

```sql theme={null}
SELECT
    type,
    event_time,
    initial_query_id,
    formatReadableSize(memory_usage) AS memory,
    `ProfileEvents.Values`[indexOf(`ProfileEvents.Names`, 'UserTimeMicroseconds')] AS userCPU,
    `ProfileEvents.Values`[indexOf(`ProfileEvents.Names`, 'SystemTimeMicroseconds')] AS systemCPU,
    normalizedQueryHash(query) AS normalized_query_hash
FROM clusterAllReplicas(default, merge(system, '^query_log'))
ORDER BY memory_usage DESC
LIMIT 10
```

<div id="merges-in-progress-with-eta">
  ### 正在进行的合并及预计完成时间
</div>

此查询显示集群中当前正在执行的合并及其预计完成时间：

```sql theme={null}
SELECT
    hostName(),
    database,
    table,
    round(elapsed, 0) AS elapsed_seconds,
    round(progress, 4) AS progress_ratio,
    formatReadableTimeDelta((elapsed / progress) - elapsed) AS estimated_time_remaining,
    num_parts,
    result_part_name
FROM clusterAllReplicas(default, merge(system, '^merges'))
ORDER BY (elapsed / progress) - elapsed ASC
```

<div id="most-common-queries-by-normalized-hash">
  ### 按归一化哈希统计的最常见查询
</div>

查找执行次数最多的查询 (有助于识别哪些查询需要优化) ：

```sql theme={null}
SELECT
    normalizedQueryHash(query) AS query_hash,
    count() AS execution_count,
    any(query) AS example_query
FROM clusterAllReplicas(default, merge(system, '^query_log'))
WHERE event_date >= today() - 1
GROUP BY normalizedQueryHash(query)
ORDER BY execution_count DESC
LIMIT 20
```

<div id="error-counts-by-event-type-and-date">
  ### 按事件类型和日期统计错误数
</div>

分析整个集群中的 part 创建错误：

```sql theme={null}
SELECT
    event_date,
    event_type,
    table,
    error,
    COUNT() AS error_count
FROM clusterAllReplicas(default, merge(system, '^part_log'))
WHERE database = 'default'
GROUP BY
    event_date,
    event_type,
    error,
    table
ORDER BY
    event_date DESC,
    error_count DESC
```

<div id="number-of-tables-by-node">
  ### 按节点统计的表数量
</div>

查看集群各节点上的表分布：

```sql theme={null}
SELECT
    hostName() AS host,
    count() AS table_count
FROM clusterAllReplicas('default', merge(system, '^tables'))
WHERE database = 'default'
GROUP BY hostName()
ORDER BY table_count DESC
```

<div id="check-for-async-insert-operations">
  ### 查看异步插入操作
</div>

监控异步插入情况：

```sql theme={null}
SELECT
    event_date,
    count() AS total_count,
    sum(if(query LIKE '%async%', 1, 0)) AS async_count,
    sum(if(query LIKE '%INSERT%', 1, 0)) AS insert_count
FROM clusterAllReplicas(default, merge(system, '^query_log'))
WHERE event_date >= today() - 7
GROUP BY event_date
ORDER BY event_date DESC
```

<div id="parts-and-merges-analysis">
  ## Parts 和合并分析
</div>

<div id="currently-active-parts-by-table">
  ### 各表当前活跃的 parts
</div>

查看整个集群中每个表当前活跃的 parts 数量：

```sql theme={null}
SELECT
    database,
    table,
    count() AS part_count,
    formatReadableSize(sum(bytes_on_disk)) AS total_size
FROM clusterAllReplicas(default, system.parts)
WHERE active = 1 AND database = 'default'
GROUP BY database, table
ORDER BY part_count DESC
```

<div id="partitions-with-too-many-parts">
  ### parts 过多的分区
</div>

找出 parts 可能过多的分区 (这可能会影响查询性能) ：

```sql theme={null}
SELECT
    database,
    table,
    partition,
    count() AS part_count,
    formatReadableSize(sum(bytes_on_disk)) AS total_size
FROM clusterAllReplicas(default, system.parts)
WHERE active = 1
GROUP BY database, table, partition
HAVING part_count > 100
ORDER BY part_count DESC
```

<div id="detached-parts">
  ### 已分离 parts
</div>

检查可能需要调查的已分离 parts：

```sql theme={null}
SELECT
    database,
    table,
    partition_id,
    name,
    reason,
    count()
FROM clusterAllReplicas(default, system.detached_parts)
GROUP BY database, table, partition_id, name, reason
ORDER BY database, table
```

<div id="system-information-queries">
  ## 系统信息查询
</div>

<div id="cluster-wide-memory-usage-by-node">
  ### 按节点查看集群级内存使用情况
</div>

监控各节点的内存使用情况：

```sql theme={null}
SELECT
    hostName() AS host,
    formatReadableSize(max(memory_usage)) AS peak_memory,
    formatReadableSize(avg(memory_usage)) AS avg_memory,
    formatReadableSize(min(memory_usage)) AS min_memory
FROM clusterAllReplicas(default, merge(system, '^query_log'))
WHERE event_date >= today() - 1
GROUP BY hostName()
ORDER BY peak_memory DESC
```

<div id="running-queries-on-the-cluster">
  ### 在集群上执行查询
</div>

查看当前正在执行的查询：

```sql theme={null}
SELECT
    hostName() AS host,
    initial_user,
    query_id,
    elapsed,
    read_rows,
    formatReadableSize(memory_usage) AS memory_usage,
    normalizedQueryHash(query) AS query_hash
FROM clusterAllReplicas(default, system.processes)
ORDER BY elapsed DESC
```

<div id="modified-settings-from-defaults">
  ### 已修改的非默认设置
</div>

查看哪些设置已偏离默认值：

```sql theme={null}
SELECT
    hostName() AS host,
    name,
    value
FROM clusterAllReplicas(default, system.settings)
WHERE changed = 1
ORDER BY hostName(), name
```

<div id="replication-queue-status">
  ### 复制队列状态
</div>

对于复制表，请查看复制队列：

```sql theme={null}
SELECT
    hostName() AS host,
    database,
    table,
    count() AS queue_size,
    sum(if(is_currently_executing = 1, 1, 0)) AS executing_count
FROM clusterAllReplicas(default, system.replication_queue)
GROUP BY hostName(), database, table
HAVING queue_size > 0
ORDER BY queue_size DESC
```
