Skip to main content
The pg_stat_ch ClickHouse schema includes four materialized views that aggregate events_raw data automatically. All views are populated by ClickHouse as events arrive — no manual refresh is needed.

Overview

The typical workflow is: use materialized views to find patterns, then drill into events_raw for specific events.

events_recent_1h

A copy of events_raw with a 1-hour TTL. ClickHouse automatically deletes events older than 1 hour from this table. Use cases:
  • “What queries ran in the last 5 minutes?”
  • Real-time dashboards with sub-second refresh
  • Quick debugging of ongoing issues
Because this table has a 1-hour TTL, queries against it are fast even if events_raw has weeks of data.

query_stats_5m

Pre-aggregated query statistics in 5-minute buckets. This is the primary view for dashboards and performance monitoring. Use cases:
  • QPS trends over time
  • Latency percentiles (p95/p99) per query
  • Identifying slow queries and regressions
  • Capacity planning

Schema

Querying aggregate states

This view uses ClickHouse’s -State / -Merge pattern. Columns store intermediate aggregate states that must be finalized with the corresponding -Merge function: This pattern allows correct re-aggregation across multiple 5-minute buckets. For example, a 1-hour p99 is computed correctly from 12 five-minute digests, rather than being an average of 12 p99 values.

Top queries by p99 latency

QPS over time

Each bucket is 5 minutes (300 seconds), so divide by 300 for per-second rate:

Cache hit ratio trend

db_app_user_1m

Load breakdown by database, application, user, and command type in 1-minute buckets. Use cases:
  • Which application is generating the most load?
  • Per-tenant or per-user resource tracking
  • Error rates by application
  • Identifying misbehaving clients

Schema

Load by application

Error rate by database and user

errors_recent

Recent error events with a 7-day TTL. This view filters events_raw to only rows where err_elevel > 0. Use cases:
  • “What errors happened in the last hour?”
  • Incident investigation with query context
  • Error rate alerting
  • Identifying recurring error patterns by SQLSTATE

Schema

This view stores the full event row (not aggregated): ts_start, db, username, app, client_addr, pid, query_id, err_sqlstate, err_elevel, err_message, query

Recent errors with context

Error breakdown by SQLSTATE

Custom views

You can create your own materialized views on top of events_raw for project-specific analytics. For example, a view that tracks queries by table name or a view that computes per-minute error rates for alerting. See the ClickHouse documentation on materialized views for details on creating and managing views.