> ## Documentation Index
> Fetch the complete documentation index at: https://help.treble.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Advanced Queries

> How the warehouse is laid out under the hood, plus a cookbook of complex queries — all tested against production.

# Advanced Queries

[Query Optimization](https://help.treble.ai/en/docs/data-warehouse-v2/query-optimization.md) 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.

| Table | Sorted by | Partitioned by |
| - | - | - |
| `fact_treble_sessions` | `company_id`, `created_at`, `session_id` | month of `created_at` |
| `fact_treble_session_messages` | `company_id`, `session_id`, `created_at`, `message_id` | month of `created_at` |
| `fact_treble_session_nodes` | `company_id`, `session_id`, `entered_at`, `node_record_id` | month of `entered_at` |
| `fact_treble_session_variables` | `company_id`, `session_id`, `variable_name`, `variable_id` | month of `created_at` |
| `fact_campaign_sends` | `company_id`, `day of scheduled_at`, `deployment_id` | month of `scheduled_at` |
| `fact_campaign_daily` | `company_id`, `poll_id`, `day` | month of `day` |
| `fact_hsm_responses` | `company_id`, `session_id`, `entered_at`, `node_record_id` | month of `entered_at` (not exposed) |
| `fact_agent_conversations` | `company_id`, `created_at`, `agent_conversation_id` | month of `created_at` |
| `fact_agent_conversation_messages` | `company_id`, `agent_conversation_id`, `created_at`, `message_id` | month of `created_at` |
| `fact_agent_conversation_transfers` | `company_id`, `agent_conversation_id`, `transfer_id` | not partitioned |
| `fact_agent_status_changes` | `company_id`, `agent_id`, `created_at`, `status_change_id` | month of `created_at` |
| `fact_agent_daily` | `company_id`, `agent_id`, `day` | month of `day` |
| `fact_target_events` | `company_id`, `created_at`, `event_id` | month of `created_at` |
| `fact_ad_sessions` | `company_id`, `created_at`, `session_id` | month of `created_at` |
| `fact_whatsapp_link_events` | `company_id`, `created_at`, `event_id` | month of `created_at` |
| `fact_ai_conversations` | `company_id`, `created_at`, `evaluation_id` | month of `created_at` |
| `dim_agents`, `dim_hsms`, `dim_tags`, `dim_teams` | `company_id`, `id` | not partitioned |
| `dim_poll_nodes` | `company_id`, `poll_id`, `node_id` | not partitioned |
| `dim_agent_tags` | `company_id`, `agent_id`, `tag_id` | not partitioned |
| `dim_ab_variants` | `company_id`, `poll_id`, `node_id`, `edge_id` | not partitioned |
| `dim_target_events` | `company_id`, `node_id`, `target_event_id` | not partitioned |
| `dim_polls`, `dim_channels` | served from memory | not partitioned |

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

> [!NOTE]
>
> 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.

```sql theme={null}
-- A) The messages that happened inside the window
SELECT count()
FROM fact_treble_session_messages
WHERE created_at >= now() - INTERVAL 3 DAY

-- B) The messages of conversations that started inside the window
SELECT count()
FROM fact_treble_session_messages
WHERE session_id IN (
        SELECT session_id
        FROM fact_treble_sessions
        WHERE created_at >= now() - INTERVAL 3 DAY)
```

> [!WARNING]
>
> 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:

| Variant | Time | Rows read |
| - | - | - |
| Date filter | 0.364 s | 1.42 million |
| Session subquery | 0.454 s | 1.92 million |

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`](https://help.treble.ai/en/docs/data-warehouse-v2/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.

> [!WARNING]
>
> 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:

```sql theme={null}
SELECT hsm_name, answer_text, count() AS answers
FROM fact_hsm_responses
WHERE responded_at >= now() - INTERVAL 7 DAY
  AND session_id IN (
        SELECT session_id
        FROM fact_treble_sessions
        WHERE created_at >= now() - INTERVAL 8 DAY)
GROUP BY hsm_name, answer_text
ORDER BY answers DESC
```

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.

```sql theme={null}
SELECT
    poll_name,
    count()                                    AS sent,
    countIf(delivered_at IS NOT NULL)          AS delivered,
    countIf(responded_at IS NOT NULL)          AS responded,
    round(100 * countIf(delivered_at IS NOT NULL) / count(), 1) AS delivery_pct,
    round(100 * countIf(responded_at IS NOT NULL)
              / nullIf(countIf(delivered_at IS NOT NULL), 0), 1) AS response_pct,
    round(quantileIf(0.50)(
        dateDiff('second', delivered_at, responded_at),
        responded_at IS NOT NULL) / 60, 1)     AS median_response_min
FROM fact_campaign_sends
WHERE scheduled_at >= now() - INTERVAL 30 DAY
GROUP BY poll_name
HAVING sent >= 1000
ORDER BY responded DESC
```

> [!NOTE]
>
> 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.

```sql theme={null}
SELECT
    n.poll_name                                     AS flow,
    substring(coalesce(d.question_text, ''), 1, 60) AS question,
    count()                                         AS reached,
    countIf(n.responded_at IS NOT NULL)             AS answered,
    round(100 * countIf(n.responded_at IS NOT NULL) / count(), 1) AS response_pct
FROM fact_treble_session_nodes AS n
LEFT JOIN dim_poll_nodes AS d
       ON d.company_id = n.company_id
      AND d.poll_id    = n.poll_id
      AND d.node_id    = n.node_id
WHERE n.entered_at >= now() - INTERVAL 30 DAY
  AND n.node_type = 'QUESTION'
GROUP BY flow, question
HAVING reached >= 1000
ORDER BY response_pct ASC
```

> [!NOTE]
>
> 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.

```sql theme={null}
SELECT
    session_id,
    maxIf(variable_value, variable_name = 'city')       AS city,
    maxIf(variable_value, variable_name = 'product')    AS product,
    maxIf(variable_value, variable_name = 'deployment') AS deployment
FROM fact_treble_session_variables
WHERE created_at >= now() - INTERVAL 7 DAY
GROUP BY session_id
```

> [!NOTE]
>
> 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:

```sql theme={null}
SELECT variable_name, count() AS times
FROM fact_treble_session_variables
WHERE created_at >= now() - INTERVAL 7 DAY
GROUP BY variable_name
ORDER BY times DESC
```

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

```sql theme={null}
SELECT
    c.team_name                               AS team,
    count()                                   AS conversations,
    countDistinct(c.agent_id)                 AS agents,
    round(quantileIf(0.50)(c.first_response_sec, c.first_response_sec > 0)) AS p50_sec,
    round(quantileIf(0.90)(c.first_response_sec, c.first_response_sec > 0)) AS p90_sec,
    round(100 * countIf(c.transfer_count > 0) / count(), 1) AS transferred_pct,
    round(100 * countIf(c.rating > 0) / count(), 1)         AS rated_pct
FROM fact_agent_conversations AS c
WHERE c.created_at >= now() - INTERVAL 30 DAY
GROUP BY team
HAVING conversations >= 200
ORDER BY p90_sec DESC
```

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

```sql theme={null}
SELECT
    poll_name,
    sumIf(sent,      day >= today() - 30 AND day < today() - 15) AS sent_previous,
    sumIf(sent,      day >= today() - 15)                        AS sent_current,
    round(100 * sumIf(responded, day >= today() - 30 AND day < today() - 15)
              / nullIf(sumIf(sent, day >= today() - 30 AND day < today() - 15), 0), 1) AS previous_pct,
    round(100 * sumIf(responded, day >= today() - 15)
              / nullIf(sumIf(sent, day >= today() - 15), 0), 1)  AS current_pct
FROM fact_campaign_daily
WHERE day >= today() - 30
GROUP BY poll_name
HAVING sent_previous >= 500 AND sent_current >= 500
ORDER BY (current_pct - previous_pct) ASC
```

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

```sql theme={null}
SELECT
    countDistinct(session_id)              AS sessions,
    round(avg(messages), 1)                AS messages_per_session,
    round(avg(from_user), 1)               AS messages_from_user,
    round(quantile(0.50)(duration_sec) / 60, 1) AS median_duration_min
FROM (
    SELECT
        session_id,
        count()                                              AS messages,
        countIf(sender = 'USER')                             AS from_user,
        dateDiff('second', min(created_at), max(created_at)) AS duration_sec
    FROM fact_treble_session_messages
    WHERE session_id IN (
            SELECT session_id
            FROM fact_treble_sessions
            WHERE created_at >= now() - INTERVAL 3 DAY)
    GROUP BY session_id)
```

> [!NOTE]
>
> 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.

```sql theme={null}
SELECT
    count()                                        AS contacts,
    countIf(sessions > 1)                          AS returned,
    round(100 * countIf(sessions > 1) / count(), 1) AS returning_pct,
    round(avg(sessions), 2)                        AS avg_sessions
FROM (
    SELECT contact_id, count() AS sessions
    FROM fact_treble_sessions
    WHERE created_at >= now() - INTERVAL 30 DAY
      AND contact_id != 0
    GROUP BY contact_id)
```

> [!NOTE]
>
> `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](https://help.treble.ai/en/docs/data-warehouse-v2/query-optimization.md#system-limits). 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](https://help.treble.ai/en/docs/data-warehouse-v2/incremental-sync.md) pattern.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.