> ## 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.

# Useful queries for monitoring and alerting

> Queries over ClickHouse system tables for dashboards and alerts: restarts, failed queries, memory limit errors, CPU usage and wait, memory, load average, failed merges.

These queries read the system tables of the server you are connected to and look at the last hour or the last day; adjust the intervals to your needs. To cover every server of a cluster, see [Run the queries on all servers of a cluster](#run-the-queries-on-all-servers-of-a-cluster). For queries that inspect tables, parts and running queries, see [Useful queries for troubleshooting](https://clickhouse.com/docs/resources/support-center/knowledge-base/queries-sql/useful-queries-for-troubleshooting.md).

The log tables used here (`system.query_log`, `system.metric_log`, `system.part_log`, `system.text_log`, `system.asynchronous_metric_log`) are enabled in the default server configuration. They are sorted by `event_date` first (`system.asynchronous_metric_log` by `metric` first), which is why the queries filter on `event_date` in addition to `event_time`: the server then reads only the recent data.

## Server start time

```sql theme={null}
SELECT
    hostName() AS host,
    now() - uptime() AS started_at,
    formatReadableTimeDelta(uptime()) AS running_for;
```

An unexpectedly small uptime means that the server was restarted. For the history of starts, search the server log in [`system.text_log`](https://clickhouse.com/docs/reference/system-tables/text_log):

```sql theme={null}
SELECT
    event_time,
    message
FROM system.text_log
WHERE event_date >= today() - 7
    AND logger_name = 'Application'
    AND message LIKE 'Starting ClickHouse%'
ORDER BY event_time DESC
LIMIT 20;
```

The server writes `Starting ClickHouse` followed by its version, revision and build identifier when it starts. Every row is one start of the server, so two rows close to each other mean a restart. The last messages before a stop are not a reliable marker: a server that is terminated abruptly does not write them.

## Failed queries by error

A query that fails is written to [`system.query_log`](https://clickhouse.com/docs/reference/system-tables/query_log) with the type `ExceptionBeforeStart` or `ExceptionWhileProcessing`:

```sql theme={null}
SELECT
    errorCodeToName(exception_code) AS error,
    count() AS failed_queries,
    uniqExact(normalized_query_hash) AS query_patterns
FROM system.query_log
WHERE event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 HOUR
    AND type IN ('ExceptionBeforeStart', 'ExceptionWhileProcessing')
GROUP BY error
ORDER BY failed_queries DESC
LIMIT 20;
```

Example output from a test instance:

```text theme={null}
   ┌─error─────────────────┬─failed_queries─┬─query_patterns─┐
1. │ MEMORY_LIMIT_EXCEEDED │              3 │              2 │
2. │ UNKNOWN_IDENTIFIER    │              1 │              1 │
3. │ UNFINISHED            │              1 │              1 │
   └───────────────────────┴────────────────┴────────────────┘
```

`normalized_query_hash` is the same for queries that differ only in literal values, so `query_patterns` tells you whether one statement fails repeatedly or many different ones fail. The query log is a better source for alerts than the counters of `system.errors`, which also count exceptions that the server handled internally: see [Why does system.errors show errors for queries that succeeded?](https://clickhouse.com/docs/resources/support-center/knowledge-base/monitoring-debugging/system-errors-shows-errors-for-successful-queries.md).

## Queries that exceeded the memory limit

Error code 241 is `MEMORY_LIMIT_EXCEEDED`. This query groups such failures by hour and by query pattern and returns one `query_id` per group to look at:

```sql theme={null}
SELECT
    toStartOfHour(event_time) AS hour,
    normalized_query_hash,
    count() AS failed_queries,
    any(query_id) AS example_query_id,
    formatReadableSize(max(memory_usage)) AS max_memory_usage
FROM system.query_log
WHERE event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 DAY
    AND type IN ('ExceptionBeforeStart', 'ExceptionWhileProcessing')
    AND exception_code = 241
GROUP BY
    hour,
    normalized_query_hash
ORDER BY
    hour DESC,
    failed_queries DESC
LIMIT 20;
```

Replace `241` with another code to track a different error, for example `202` for `TOO_MANY_SIMULTANEOUS_QUERIES`. See [Memory limit exceeded for query](https://clickhouse.com/docs/resources/support-center/knowledge-base/performance-optimization/memory-limit-exceeded-for-query.md) for what to do about the error itself.

## Peak CPU usage

[`system.metric_log`](https://clickhouse.com/docs/reference/system-tables/metric_log) stores, for every collection interval, how much each profile event grew. The interval is `collect_interval_milliseconds` in the [`metric_log`](https://clickhouse.com/docs/reference/settings/server-settings/settings/other#metric_log) section of the server configuration, 1000 (one second) by default. `OSCPUVirtualTimeMicroseconds` is the CPU time used by the server, so dividing it by the length of the interval in microseconds gives the number of CPU cores that were busy during the interval:

```sql theme={null}
WITH 1000 AS collect_interval_milliseconds
SELECT
    toStartOfInterval(event_time, INTERVAL 10 MINUTE) AS interval_start,
    round(max(ProfileEvent_OSCPUVirtualTimeMicroseconds) / (collect_interval_milliseconds * 1000), 2) AS peak_cpu_cores,
    round(avg(ProfileEvent_OSCPUVirtualTimeMicroseconds) / (collect_interval_milliseconds * 1000), 2) AS avg_cpu_cores
FROM system.metric_log
WHERE event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 HOUR
GROUP BY interval_start
ORDER BY interval_start;
```

Compare `peak_cpu_cores` with the number of cores available to the server. If your server collects the metrics at another interval, change the first line of the query: with the wrong value the result is off by the ratio of the two intervals, for example twice too high for a two-second interval.

## CPU wait

`OSCPUWaitMicroseconds` is the time that threads were ready to run but waited for a CPU core. Collection intervals in which the threads of the server waited, in total, for longer than the interval lasts (more than one second with the default interval) indicate that the server had more work than cores:

```sql theme={null}
WITH 1000 AS collect_interval_milliseconds
SELECT
    event_time,
    round(ProfileEvent_OSCPUWaitMicroseconds / 1000000, 2) AS wait_seconds
FROM system.metric_log
WHERE event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 HOUR
    AND wait_seconds > collect_interval_milliseconds / 1000
ORDER BY wait_seconds DESC
LIMIT 10;
```

## Memory tracked by the server

```sql theme={null}
SELECT
    toStartOfMinute(event_time) AS minute,
    formatReadableSize(avg(CurrentMetric_MemoryTracking)) AS avg_memory,
    formatReadableSize(max(CurrentMetric_MemoryTracking)) AS max_memory
FROM system.metric_log
WHERE event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 HOUR
GROUP BY minute
ORDER BY minute;
```

`MemoryTracking` is the total amount of memory tracked by the server.

## Memory used compared with the memory available

[`system.asynchronous_metric_log`](https://clickhouse.com/docs/reference/system-tables/asynchronous_metric_log) keeps the history of the metrics that the server calculates periodically. `MemoryResident` is the physical memory used by the server process. `CGroupMemoryTotal` is the memory limit of the cgroup (container) the server runs in, and is zero or absent when there is no such limit, in which case `OSMemoryTotal`, the memory of the host, applies:

```sql theme={null}
SELECT
    toStartOfMinute(event_time) AS minute,
    maxIf(value, metric = 'MemoryResident') AS memory_used,
    maxIf(value, metric = 'CGroupMemoryTotal') AS cgroup_memory_total,
    maxIf(value, metric = 'OSMemoryTotal') AS os_memory_total,
    if(cgroup_memory_total > 0, cgroup_memory_total, os_memory_total) AS memory_total,
    round(memory_used / memory_total, 2) AS used_ratio
FROM system.asynchronous_metric_log
WHERE metric IN ('MemoryResident', 'CGroupMemoryTotal', 'OSMemoryTotal')
    AND event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 HOUR
GROUP BY minute
ORDER BY minute;
```

## Load average

`LoadAverage15` is the load of the whole host averaged over 15 minutes; `LoadAverage1` and `LoadAverage5` are also available:

```sql theme={null}
SELECT
    toStartOfMinute(event_time) AS minute,
    round(avg(value), 2) AS load_avg,
    round(max(value), 2) AS load_max
FROM system.asynchronous_metric_log
WHERE metric = 'LoadAverage15'
    AND event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 HOUR
GROUP BY minute
ORDER BY minute;
```

## Failed merges and mutations

Every merge and every mutation of a part is recorded in [`system.part_log`](https://clickhouse.com/docs/reference/system-tables/part_log). A non-zero `error` is the code of the exception that stopped it:

```sql theme={null}
SELECT
    event_time,
    database,
    table,
    event_type,
    part_name,
    errorCodeToName(error) AS error_name,
    splitByChar('\n', exception)[1] AS exception_first_line
FROM system.part_log
WHERE event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 DAY
    AND event_type IN ('MergeParts', 'MutatePart')
    AND error != 0
ORDER BY event_time DESC
LIMIT 20;
```

Background operations are retried, so one cause can produce many rows. For a mutation that keeps failing, see [How to find the oldest unfinished mutation and kill stuck mutations](https://clickhouse.com/docs/resources/support-center/knowledge-base/monitoring-debugging/find-oldest-unfinished-mutation.md).

## Run the queries on all servers of a cluster

Each server has its own system tables. To query all of them at once, wrap the table in [`clusterAllReplicas`](https://clickhouse.com/docs/reference/functions/table-functions/cluster) and add `hostName()` to the result. In ClickHouse Cloud the cluster is named `default`; on a self-managed cluster use the name from `system.clusters`:

```sql theme={null}
SELECT
    hostName() AS host,
    errorCodeToName(exception_code) AS error,
    count() AS failed_queries
FROM clusterAllReplicas('default', system.query_log)
WHERE event_date >= yesterday()
    AND event_time >= now() - INTERVAL 1 HOUR
    AND type IN ('ExceptionBeforeStart', 'ExceptionWhileProcessing')
GROUP BY
    host,
    error
ORDER BY failed_queries DESC;
```
