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

> Queries to help you debug memory issues.

# Debugging memory issues

When encountering memory issues or a memory leak, knowing what queries and resources are consuming a significant amount of memory is helpful. Below you can find queries that can help you to debug memory issues by finding which queries, databases, and tables can be optimized:

<h2 id="list-currently-running-processes-by-peak-memory">
  List currently running processes by peak memory usage
</h2>

```sql theme={null}
SELECT
    initial_query_id,
    query,
    elapsed,
    formatReadableSize(memory_usage),
    formatReadableSize(peak_memory_usage),
FROM system.processes
ORDER BY peak_memory_usage DESC
LIMIT 100;
```

<h2 id="list-metrics-for-memory-usage">
  List metrics for memory usage
</h2>

```sql theme={null}
SELECT
    metric, description, formatReadableSize(value) size
FROM
    system.asynchronous_metrics
WHERE
    metric LIKE '%Cach%'
    OR metric LIKE '%Mem%'
ORDER BY
    value DESC;
```

<h2 id="list-tables-by-current-memory-usage">
  List tables by current memory usage
</h2>

```sql theme={null}
SELECT
    database,
    name,
    formatReadableSize(total_bytes)
FROM system.tables
WHERE engine IN ('Memory','Set','Join');
```

<h2 id="output-total-memory-used-by-merges">
  Output total memory used by merges
</h2>

```sql theme={null}
SELECT formatReadableSize(sum(memory_usage)) FROM system.merges;
```

<h2 id="output-total-memory-used-by-currently-running-processes">
  Output total memory used by currently running processes
</h2>

```sql theme={null}
SELECT formatReadableSize(sum(memory_usage)) FROM system.processes;
```

<h2 id="output-total-memory-used-by-dictionaries">
  Output total memory used by dictionaries
</h2>

```sql theme={null}
SELECT formatReadableSize(sum(bytes_allocated)) FROM system.dictionaries;
```

<h2 id="output-total-memory-used-by-primary-keys">
  Output total memory used by primary keys and index granularity
</h2>

```sql theme={null}
SELECT
    sumIf(data_uncompressed_bytes, part_type = 'InMemory') AS memory_parts,
    formatReadableSize(sum(primary_key_bytes_in_memory)) AS primary_key_bytes_in_memory,
    formatReadableSize(sum(primary_key_bytes_in_memory_allocated)) AS primary_key_bytes_in_memory_allocated,
    formatReadableSize(sum(index_granularity_bytes_in_memory)) AS index_granularity_bytes_in_memory,
    formatReadableSize(sum(index_granularity_bytes_in_memory_allocated)) AS index_granularity_bytes_in_memory_allocated
FROM system.parts;
```
