Skip to main content

Advanced Queries

Query Optimization covers the principles. This page goes one level deeper: how the warehouse is built internally, and a cookbook of queries that answer real business questions. Every query on this page was run against the production warehouse before publishing. Where a measured cost appears, it is that query’s real cost.

How each table is sorted

ClickHouse doesn’t use indexes the way a relational database does. It uses two things:
  • The sorting key — the physical order of rows on disk. A filter on the leading columns of this key lets ClickHouse jump straight to the block it needs.
  • The partition key — how data is split into physical folders. Every large table is partitioned by month.
Knowing which is which changes how you write a query.

Two families, two strategies

That table splits into two groups that you query differently. Tables sorted by time. fact_treble_sessions, fact_agent_conversations, fact_campaign_sends, fact_target_events, fact_ad_sessions, fact_whatsapp_link_events and fact_ai_conversations carry the time column right after company_id. A date filter uses both the partition and the sorting key. On these tables, a date range is enough. Tables sorted by their parent. fact_treble_session_messages, fact_treble_session_nodes, fact_treble_session_variables and fact_agent_conversation_messages are sorted by session_id or agent_conversation_id before the timestamp. A date filter on these still drops whole partitions — which already helps a lot — but within each month it has to scan through. These are the largest tables in the warehouse, so they’re worth helping.
The four detail tables are by far the heaviest: fact_treble_session_variables and fact_treble_session_messages each hold billions of rows. Even so, a date filter performs well on them: the monthly partition does most of the work.

Filtering by date and filtering by session are not the same

On the detail tables there are two ways to narrow the scope, and they are not interchangeable: they answer different questions.
These two queries return different numbers. Measured on a real account over a 3-day window, the first found 12,831 sessions and the second 12,389. The difference is conversations that cross the edge of the window: 1,802 recent messages belonging to sessions that opened before it started. Choose based on what you mean to count, not on performance.
Use A to measure activity — “how many messages were there this week”. Use B to measure cohorts — “how did the conversations that started this week behave”. B is the correct one when you compute per-session totals such as duration or messages per conversation, because a date filter cuts conversations in half at the window edge.

The date filter already performs well

It might look as though narrowing by session helps performance on the tables sorted by session_id. It does not. Both forms, measuring the same thing over a 30-day window: The date filter wins because the monthly partition already discards almost everything, and company_id — which your user carries automatically — is the leading column of the sorting key. The subquery adds work rather than removing it: the sessions table has to be read too. Filter by date. Reach for the subquery only when the question is about a cohort.

The exception: fact_hsm_responses

fact_hsm_responses is not a table of its own: it is a filtered view over fact_treble_session_nodes —only the template steps that got an answer—. It inherits that table’s sorting and partitioning, and the partition is by entered_at (when the template was sent), a column this view does not expose. That is why a filter on responded_at prunes nothing: it scans your account’s entire history.
Measured on a large account: WHERE responded_at >= now() - INTERVAL 7 DAY read 74.7 million rows, above the 50 million limit, so the query fails. Scoped by session, the same question read 6.5 million.
Here the session subquery is the way to scope. Give it a one-day margin to include answers to templates sent just before the window:
Answers to sessions that started before the margin are left out; widen the margin if you need them.

Cookbook

Real business questions, each answered by a single query. None of them need company_id — your user already carries it.

1. The funnel for every campaign

How many went out, how many arrived, how many replied, and how long they took — per flow, in one comparable table.
Measured cost: 0.35 s, 202 thousand rows read, 62 MiB of memory.

2. Which question loses people

The most actionable query in the warehouse. It joins the nodes people walked through with the real text of each question, and sorts by the worst response rate.
Measured cost: 0.61 s, 825 thousand rows read, 193 MiB of memory.
Sorting ascending by response_pct puts the questions that lose the most people on top. A node with heavy traffic and a near-zero response rate is often an informational message that never expected a reply — worth confirming before treating it as a problem.

3. Session variables as columns

Variables are stored as rows (variable_name, variable_value). For analysis you almost always want them as columns. maxIf does the pivot.
Measured cost: 0.15 s, 470 thousand rows read, 74 MiB of memory.
Replace 'city' and 'product' with your own variable names. To discover which ones you have:

4. Team ranking with percentiles

The median hides the tail. Asking for p50 and p90 together shows which team is consistent and which one has cases left hanging.

5. Compare two periods

On the daily rollup, which is the table built for this. Sorting by the drop puts what got worse on top.

6. The shape of a conversation

How many messages a session holds, how many the person contributed, and how long it ran end to end.
Here the session subquery is the right call: you are computing per-session totals, and a date filter would cut conversations that cross the window edge. Measured cost: 3.98 s, 550 thousand rows read, 115 MiB of memory. This is the most expensive recipe on the page: it groups by session across the messages table. Widen the window carefully.

7. Contacts who come back

How much of your activity is new people, and how much is the same people returning.
contact_id = 0 means the session was never linked to a contact. Leave it out when counting people.

Things worth knowing

The first run can be much slower. ClickHouse caches the blocks it reads. A query that takes fifteen seconds the first time may take under one second the second time. If a new query feels slow, run it again before rewriting it. SELECT * is expensive on the message tables. The text and content columns are wide, as is ai_automator_instructions in dim_poll_nodes. Naming only the columns you need can change a query’s cost by an order of magnitude. The right side of a JOIN is loaded into memory. Put the small table there — dimensions always are. And join on company_id alongside the id, as every example on this page does. The daily tables exist for dashboards. If your question can be answered from fact_campaign_daily or fact_agent_daily, use them: they read thousands of rows instead of millions. Threshold HAVING clauses cut the noise. A HAVING sent >= 1000 keeps twenty-message campaigns — whose percentages mean nothing — out of your table.

When you hit a limit

The system limits live in Query Optimization. In order, what almost always fixes it:
  1. Narrow the date range.
  2. Drop the ORDER BY if you do not need it, and avoid countDistinct on high-cardinality columns.
  3. Drop wide columns from the SELECT.
  4. Aggregate with GROUP BY instead of pulling raw rows.
  5. Split the extract into one-month chunks — or better, move to the Incremental Sync pattern.