# Insights, dashboards and SQL

> Chart trends, funnels, retention, paths, stickiness and lifecycle, save them to dashboards with alerts and email subscriptions, and query raw events with SQL or the query API.

Source: https://apphelm.dev/docs/insights

An **insight** is a question about your events, answered as a chart: how many people signed up each week, how many of them reached checkout, how many came back. AppHelm has six kinds: trends, funnels, retention, paths, stickiness and lifecycle. You build them in **Analytics → Insights**, save them, put them on dashboards, get alerted when a line crosses a threshold, and have them emailed on a schedule.

When a chart is not enough, **Analytics → SQL** runs read-only SQL over the same events, people and sessions. Both are also available through the API, so a script, a notebook or an AI agent gets the same numbers you see in the app.

Insights read the events your SDKs send. If you have not sent any yet, start with [Events and autocapture](https://apphelm.dev/docs/events) and [Users, people and groups](https://apphelm.dev/docs/identify).

## How insights count

A few rules apply to every insight. Knowing them avoids most "why is this number different" questions.

- **Time is UTC, and it is the time AppHelm received the event.** Days, hours, ISO weeks (starting Monday) and calendar months are all UTC buckets. The device's own clock is kept (`client_timestamp` in SQL) but charts do not use it, because device clocks are often wrong.
- **A person is a person across sign-in.** Unique people are counted by a pair of hashes of the distinct id, never the raw id. Funnels and retention follow sign-in links (`$identify`, `$create_alias`), so the anonymous visitor who signed up and the signed-in user count as one person.
- **Ranges are capped and never quietly shortened.** A range is `days` ending today or a custom `dateFrom`–`dateTo` (whole UTC days, both inclusive). Most insights cover at most 90 days; see [Limits](#limits). A range that reaches past your plan's capture retention is cut at the retention boundary and the result says so, because those events have been deleted.
- **Every result carries a caveat**: one sentence saying what was counted, over which range, and what was left out. Read it when a number surprises you.
- **Anonymous events** (no distinct id) count in event totals. Stickiness leaves them out, because counting intervals per person needs a stable id.

## Build an insight

### Open the builder
Go to **Analytics** and press **Build an insight**, or open the **Insights** tab. Choose the product in the product selector.

### Choose a kind
Pick **Trend**, **Funnel**, **Retention** or **Path** under **Kind**. Stickiness and lifecycle are trends with a different **Display**.

### Choose events and options
Pick the event (or funnel steps), then add filters, a breakdown and a date range. Press **Run**. The result, its data table and the people behind it appear beside the options.

### Save it
Press **Save**, give it a name, and it appears under **Saved**. Saving needs a workspace owner or admin. From a saved insight you can **Add to dashboard**, **Share**, set an alert or **Subscribe**.

> **Start from data you already have:** Add the **demo product** in Setup to try every insight kind on 30 days of sample data. The demo product is read-only: you can run insights on it but not save or annotate them.

## Trends

A trend counts an event per interval. It is the default kind and the one most dashboards are made of.

| Option | Values | Notes |
| --- | --- | --- |
| Interval | `hour`, `day`, `week`, `month` | Hours cover 14 days at most; weeks 182 days; months 365 days |
| Math | `total` (events), `people` (unique people), `sessions`, `groups` | `groups` counts distinct groups of one type, such as `company` |
| | `weekly_active`, `monthly_active` | People active in the 7 or 30 days ending each bucket |
| | `sum`, `avg`, `min`, `max`, `median`, `p90`, `p95`, `p99` | Of a numeric event property; non-numeric values are left out, and empty buckets have no value |
| Series | Up to 4 events, lines A to D | Each with its own math and up to 3 filters of its own |
| Formula | `A`–`D`, numbers, `+ - * /`, parentheses | For example `B/A*100` for a conversion rate. Buckets that divide by zero are left out |
| Compare | on or off | Adds the previous period of the same length, lined up bucket by bucket |
| Cumulative | on or off | Running totals; unique counts add each person once, when first seen |
| Smoothing | 7 or 28 days | A rolling average; daily trends only |

Buckets are dense: every bucket in the range is returned, with zero where nothing happened, so comparisons and rolling averages line up.

### Stickiness

Stickiness answers "how often do people come back?". Of the people who did the event in the range, it shows how many did it on exactly 1, 2, 3 … N distinct days (or hours, weeks or months). A product people use daily has a long tail to the right. Only identified events count.

### Lifecycle

Lifecycle splits the people who did an event in each period into four groups:

| Group | Means |
| --- | --- |
| New | Their first time doing the event |
| Returning | Also did it the period before |
| Resurrecting | Did it at some point before, but not the period before |
| Dormant | Did it the period before, not this one (drawn as a negative bar) |

Choose the period with **Granularity**: the last 24 hours, 14 days, 8 weeks or 6 months. "First time" means the first such event AppHelm still stores, so a person whose earlier events aged out under capture retention reads as new.

## Funnels

A funnel shows how many people get through a sequence of steps, and where the rest drop off.

| Option | Values | Notes |
| --- | --- | --- |
| Steps | 2 to 6 events | Each step can have up to 3 filters of its own |
| Order | `ordered` (default), `strict`, `any` | Ordered: each step after the one before, other events in between allowed. Strict: each step must be the person's very next event. Any: the steps in any order |
| Conversion window | A number of `minute`, `hour`, `day` or `week`, up to 90 days | Later steps count only within this time of the person's first step. Without one, any later step in the range counts |
| Exclusions | Up to 3 events, each between two steps | A person who does the event between those steps is excluded and counted separately |
| Breakdown | See [Breakdowns and filters](#breakdowns-and-filters) | One funnel per value |
| Correlation | on or off, plus up to 3 property keys | Events and property values that are over- or under-represented among people who converted |

Every time a person does the first step starts an attempt, and the attempt that gets furthest is the one that counts. Each step reports its count, its conversion rate and the average, median and 90th percentile time from the step before. The result also has a time-to-convert histogram and conversion over time.

Correlation uses odds ratios with Fisher's exact test, adjusted for many comparisons (Benjamini–Hochberg), so a listed event is unlikely to be chance. It shows association, not cause.

From a funnel you can open the replays of people who dropped off, and save the people who dropped off or converted at a step as a static cohort.

> **Very large funnels:** A funnel reads at most 100,000 event rows. Past that, it covers the first people only and the caveat says so. Narrow the range or add a filter to get a complete answer.

## Retention

Retention asks "of the people who started, how many came back?". Each row is a cohort of people who did the **start event** in one period; column *k* counts how many of them did the **return event** *k* periods later.

| Option | Values | Notes |
| --- | --- | --- |
| Start event | Any event | Without one, any page or screen view |
| Return event | Any event | Can be the same as the start event |
| Filters | Up to 3 on each event | |
| Granularity | `day`, `week` (default), `month` | |
| Periods | Days: 2–31 (default 14). Weeks: 2–26 (default 8). Months: 2–12 (default 6) | |
| Type | `recurring` (default), `first_time` | Recurring: everyone who did the start event in a period. First time: people only in the period they first did it |

Days are complete UTC days, weeks are rolling 7-day periods ending at the start of today, and months are calendar months. Only periods that have ended are filled, so the table is a triangle. Retention reads its own periods and does not take a date range.

## Paths

Paths show the routes people take through your product, one session at a time.

| Option | Values | Notes |
| --- | --- | --- |
| Nodes | `views` (default), `events`, `all` | Views are page paths and screen names. Events are other event names, without capture noise such as `$pageleave`, `$autocapture` and `$web_vitals` |
| Start point | A page, screen or event | Follow sessions from their first visit to it |
| End point | A page, screen or event | The steps leading to it; with a start point, the steps between the two |
| Steps | 2–10 (default 5) | |
| Exclude | Up to 10 nodes | Left out of every path |
| Cleaning | Up to 5 regular expression rules | Turn `/users/123` into `/users/:id` so ids do not split one page into thousands |

A path is one browser session in time order. Server and mobile events without a session count as one path per person per UTC day. Repeats of the same node in a row collapse into one step, and each step keeps its 10 most common moves.

A cleaning rule such as `{ "pattern": "/users/\\d+", "replacement": "/users/:id" }` is a regular expression of at most 200 characters. Patterns with nested repetition such as `(a+)+` are refused, because they can take a very long time to run.

## Breakdowns and filters

**Filters** narrow every event an insight reads. Up to 5 apply to the whole insight:

```json
[
  { "key": "plan", "operator": "equals", "value": "pro" },
  { "key": "utm_source", "operator": "is_set" },
  { "key": "role", "operator": "equals", "value": "admin", "type": "person" },
  { "type": "cohort", "key": "seg_…", "operator": "in" }
]
```

- `key` is a stored field (`path`, `referrer`, `utm_source`, `utm_medium`, `utm_campaign`, `variant`) or any event property.
- Operators: `equals`, `not_equals`, `contains`, `gt`, `lt`, `is_set`, `is_not_set`.
- `"type": "person"` tests a trait of the person behind the event: the newest value on their profile, standard-sensitivity traits only.
- `"type": "cohort"` with `in` or `not_in` tests membership of a cohort (static or dynamic).

**Breakdowns** split trends, funnels and retention by a value:

| Breakdown | Splits by |
| --- | --- |
| `path`, `referrer`, `utm_source`, `variant`, `product` | A stored field |
| `property:<key>` | An event property, such as `property:$browser` |
| `person:<trait>` | A person trait of standard sensitivity, such as `person:plan` |
| `group:<type>` | The group the event belongs to, such as `group:company` |
| `cohort:<id>[,<id>…]` | Membership of up to 5 cohorts; a person in several counts in each |

The 10 most common values are kept, the rest are folded into `(other)`, and events without a value show as `(none)`. Trends can keep 1 to 25 values (`breakdownLimit`) and break down by two things at once (`breakdowns`); a cohort breakdown stands alone.

## Cohorts

A cohort is a set of people you can filter and break down by, and that flags, surveys and experiments can target. AppHelm calls them **segments** in the app (**Segments** in the sidebar).

- **Dynamic** cohorts are defined by conditions and their membership is recomputed.
- **Static** cohorts are a fixed list: made from a CSV of distinct ids or emails (up to 10,000), from the people in an insight result (**Save these people as a cohort** on a trend, or the drop-offs or conversions of a funnel step), or by freezing a dynamic segment's current members.

Distinct ids and emails in a static cohort are hashed on the way in and never stored. An email only matches customers whose server sent the SHA-256 of the lower-case address as `verifiedEmailHash`; emails that match no one are counted as unmatched. [Users, people and groups](https://apphelm.dev/docs/identify) explains identities and traits.

## Saved insights

A saved insight stores its kind and query, so it runs fresh every time it is opened, put on a dashboard, shared or emailed.

- Names and descriptions are free text. Tags: up to 10 per insight, each 1 to 32 letters, digits, spaces, dots, dashes or underscores, stored in lower case.
- A query is at most 12,000 characters of JSON.
- **Saved** lists them with search and filters by product, kind, tag and creator. Pin up to six to the portfolio home.
- Edits are checked for conflicts: if someone else saved a change first, yours is refused rather than overwriting theirs.
- Deleting a saved insight also deletes its dashboard tiles, alerts, subscriptions and share links.

**Annotations** mark a day on every trend chart of a product (a release, a campaign, an outage). Owners and admins add them by clicking a day on a trend, or through the API. A note is 1 to 280 characters.

## Dashboards

A dashboard is a grid of saved insights and text cards. Open **Analytics → Dashboards** and press **New dashboard**, or start from a template:

| Template | Contains |
| --- | --- |
| Product analytics starter | Views per day, daily active people, stickiness, lifecycle, weekly retention, top paths, and a view-to-conversion funnel when you choose a conversion event |
| Web analytics | Pageviews, unique visitors, and pageviews by page, referrer and UTM source, plus top paths |
| Errors and performance | SQL insights for top issues, transaction p95, failure rate and exceptions per day |

Each template tile is an ordinary saved insight you can open and change.

**Dashboard filters.** A dashboard can have its own date range and up to 5 property filters. The dashboard's range replaces each tile's own range. Its property filters come first, then each tile's own, up to the limit of 5; the result notes when some of a tile's filters were left out. Dashboard property filters do not apply to SQL insights.

| Limit | Value |
| --- | --- |
| Dashboards per workspace | 20 |
| Insight tiles per dashboard | 12 |
| Text cards per dashboard | 8 |
| Tile widths | 3, 4, 6, 8 or 12 columns (insights default to 6, text to 12) |

Deleting a dashboard keeps its saved insights.

## Alerts on insights

An insight alert watches one value of a saved **trend** and notifies you when it crosses a threshold. Open the saved insight and press **New alert**.

| Field | Values |
| --- | --- |
| Line | One series or breakdown value, or **Total of every line** |
| Condition | `above` or `below` a number; `increase_pct` or `decrease_pct` from the period before (the threshold is a percentage above 0, such as `20`) |
| Interval | `hour`, `day`, `week`, `month` |
| Check current period | Off: the last complete period is checked. On: the period in progress is checked every hour |
| Channels | `email`, `slack`, `webhook` (at least one) |
| Recipients | Up to 20 members who can see the product; needs the email channel. Without a list, everyone who can see the product is emailed |

Daily, weekly and monthly alerts are checked about ten minutes after the period closes; hourly alerts and current-period alerts every hour. An alert **fires** when its condition holds and **resolves** when it no longer does. Each change is delivered once: by email, to Slack, and as a signed `insight.alert` or `insight.resolved` webhook. Each alert keeps its last 100 checks under **History**.

Only trends over time can carry an alert. Funnels, retention, paths, stickiness, lifecycle and SQL insights have no single value per period. An alert whose insight can no longer run (it was changed into a funnel, say) moves to the **errored** state with the reason and is retried hourly. An insight carries at most 10 alerts, and a workspace at most 100.

## Email subscriptions

A subscription emails a saved insight or a whole dashboard to members on a schedule. Open it and press **Subscribe**.

| Field | Values |
| --- | --- |
| Frequency | `daily`, `weekly`, `monthly` |
| Day | Weekly: `weekday` 0–6 (0 is Monday). Monthly: `monthDay` 1–28 |
| Hour | `hourUtc` 0–23 |
| Recipients | 1 to 20 members who can see what is sent |

Each recipient gets their own email with the numbers and a small table per insight (no images). Recipients are checked again before every send, so someone who lost access gets nothing. A send that fails is retried hourly until the next scheduled time, and every attempt is shown in the subscription's history. **Send me a test** sends one now. Up to 10 subscriptions per insight or dashboard and 100 per workspace.

## Share links

**Share** on a saved insight or dashboard creates a read-only link for someone outside the workspace. The link shows the chart with text redacted, and nothing else in your workspace.

- The link's token is shown once. Links expire after 1 hour to 30 days (7 days by default) and can be revoked at any time.
- An optional password protects the link. Ten wrong attempts lock it for 15 minutes.
- A link stops working if the person who created it loses the right to share it.

## SQL

**Analytics → SQL** runs read-only SQL over one product's data. The dialect is PostHog's HogQL style on SQLite: `count()`, `uniq()`, `countIf()`, `toStartOfWeek()`, `dateDiff()`, `properties.$browser`, `person.properties.plan` and `now() - INTERVAL 7 DAY` all work.

```sql
SELECT toStartOfWeek(timestamp) AS week,
       uniq(person_id) AS people,
       countIf(properties.plan = 'pro') AS pro_signups
FROM events
WHERE event = 'signup_completed'
GROUP BY week
ORDER BY week
```

Press **Run** (or Ctrl/Cmd + Enter). Results show as a table or a chart and download as **CSV**. **Save query** keeps a query by name for everyone who can see the product; **History** holds your last 100 runs (the query and how it went, never the rows). **Ask a question** drafts a query from plain English for you to review; it is sent table and property names, never rows, and uses AI credits.

A query can only read the product it runs on. It never reaches a real database table, another product or another workspace, and it cannot write.

### Tables

| Table | One row per | Date range applies |
| --- | --- | --- |
| `events` | Event: `uuid`, `event`, `timestamp`, `client_timestamp`, `distinct_id`, `person_id`, `session_id`, `properties`, `pathname`, `referrer`, `utm_source`, `utm_medium`, `utm_campaign`, `flag_key`, `variant`, `lcp_ms`, `inp_ms`, `cls`, `scroll_depth`, `autocaptured`, `replay_session_id`, and `person.*` | Yes |
| `persons` | Person: `id`, `person_id`, `created_at`, `updated_at`, `lifecycle_state`, `properties` (customer traits of standard sensitivity), `stated_properties` (what a browser `identify` stated) | No |
| `sessions` | Browser session: start and end, `duration`, `event_count`, `pageview_count`, `is_bounce`, entry and exit page, entry referrer and UTM fields, `replay_session_id` | Yes |
| `groups` | Group a server named with `$groupidentify`: `key`, `group_type`, `name`, `plan`, `lifecycle_state`, `properties` | No |
| `cohort_members` | Cohort member: `cohort_id`, `cohort_name`, `cohort_type`, `profile_id`, `person_id` | No |
| `llm_generations` | LLM generation or embedding, metadata only: model, provider, tokens, `total_cost_usd`, `latency_ms`, `is_error`. Prompts and completions are never readable | Yes |
| `exceptions` | `$exception` event: `type`, `message` (scrubbed), `level`, `handled`, `release`, `environment`, `trace_id`, `issue_id` | Yes |
| `issues` | Error issue (up to 2,000): `title`, `status`, `count`, `users`, `first_seen`, `last_seen`, `priority` | No |
| `transactions` | Sampled transaction: `name`, `op`, `status`, `duration_ms`, `release`, and `measurements.*` (web vitals, app start, frames) | Yes |
| `spans` | Indexed span: `module` (`db`, `http`, `cache` …), `description`, `duration_ms`, HTTP, database and cache fields. Up to 5,000 a day per product, kept 30 days | Yes |
| `fx_rates` | European Central Bank daily rate: `day`, `currency`, `per_eur`, `to_base` | No |

Tables that your **data sources** synced (Stripe, HubSpot, Postgres, files and more) are tables too, under their SQL names such as `stripe_charges` or `postgres_public_orders`. Their `person_id` column matches `events.distinct_id`, so you can join revenue to behaviour. `GET /api/v1/warehouse/tables?productId=prd_…` lists them with their columns. [Data pipelines, imports and exports](https://apphelm.dev/docs/data-pipelines) explains how to connect a source.

Some details that matter when you write queries:

- `distinct_id` and `person_id` are hash pairs, never the raw id. Count people with `uniq(person_id)`; join events to people on `person_id`.
- `properties.$browser`, `properties.plan` and `properties['plan']` read one key. Device context is in `$browser`, `$os`, `$device_type` and `$country`. `true` and `false` read as `1` and `0`.
- Times are UTC ISO 8601 text, so `timestamp >= '2026-10-01'` works.
- Names, emails and traits marked PII, restricted or prohibited are never readable.

### Functions

Aggregates (`count`, `countIf`, `sum`, `sumIf`, `avg`, `min`, `max`, `uniq`, `uniqIf`, `any`, `groupArray`, `group_concat` …), window functions (`row_number`, `rank`, `lag`, `lead`, `cume_dist`, `ntile` …, and any aggregate with `OVER`), text, logic (`if`, `multiIf`, `coalesce` …), numbers, type casts, UTC dates (`toStartOfDay`, `toStartOfWeek`, `toStartOfMonth`, `dateDiff`, `dateAdd`, `formatDateTime` …), JSON (`JSONExtractString` and friends) and currencies (`convert_currency`, `base_currency`). Function names are case-insensitive. `WITH`, subqueries, `UNION`, `INTERSECT`, `EXCEPT`, `CASE`, `CAST`, `INTERVAL`, `LIKE` and `ILIKE` all work.

Not available: `quantile` and `median` (use `cume_dist()` over a window, or a trend's percentile maths), `argMax`/`argMin` (use `row_number() OVER (…)` and keep row 1), regular expressions (use `LIKE`), arrays and lambdas, `RIGHT` and `FULL` joins (swap the tables and use `LEFT JOIN`), `LIMIT … BY` and `SAMPLE`. Each refusal names the alternative.

```sql
-- p95 duration of each database statement
WITH ranked AS (
  SELECT description, duration_ms,
         cume_dist() OVER (PARTITION BY description ORDER BY duration_ms) AS share
  FROM spans WHERE module = 'db'
)
SELECT description, min(duration_ms) AS p95_ms
FROM ranked WHERE share >= 0.95
GROUP BY description ORDER BY p95_ms DESC LIMIT 20
```

### SQL insights

**Save as insight** in the editor turns a query into a saved insight drawn as a `table`, `line`, `bar` or `number`, with a chosen x column and up to 6 y columns. It works on dashboards, share links and email subscriptions like any other insight, returns at most 1,000 rows, and must finish within 15 seconds. A dashboard's range replaces its own; its property filters do not apply. Alerts do not apply. **Edit** on a SQL insight opens it in the SQL editor.

### SQL limits

| Limit | Value |
| --- | --- |
| Rows | 100 without a `LIMIT`; `LIMIT` up to 10,000 (a larger one is cut and says so). CSV without a `LIMIT` returns 10,000 |
| Date range | 30 days by default, up to 365, never past your plan's capture retention. Applies to `events`, `sessions`, `llm_generations`, `exceptions`, `transactions` and `spans` |
| Query size | 20,000 characters, 40 levels of nesting, 5,000 expressions, 200 output columns |
| Table reads | 12 per query (read a table once in `WITH` and reuse it) |
| Text values | 100 distinct text values and property keys per query; `IN (…)` up to 500 values |
| Scan | 500,000 rows per query, estimated before it runs. Reading every event (no event filter) over more than 90 days must fit this budget |
| Time | 20 seconds |
| Concurrency | One running query per workspace |
| Rate | 60 runs a minute per workspace, shared by the editor, the API and MCP. Dashboard and insight renders do not count |

A subquery that refers to the row around it (a correlated `IN`, `EXISTS` or value over an event table) is refused, because it would scan the table once per row; use a `JOIN` or `WITH` instead. A cross join of two event or data-source tables is refused; join them with `ON`.

Every role except billing can run SQL and save queries on the products they can see. Saving a SQL insight needs an owner or admin.

## The query API

`GET /api/v1/query` runs the same insight engine as the builder, for one product. It returns aggregates only (counts, cohorts, paths), never single events or people.

- **Key:** a workspace server key (`ahl_live_…`) with `metrics:read`, which new keys have by default. [Keys, scopes and environments](https://apphelm.dev/docs/keys-and-environments) explains scopes.
- **Rate:** 60 requests a minute per key.
- **Parameters:** `productId` and `kind` (`trend`, `funnel`, `retention`, `path` or `web`) are required. Stickiness and lifecycle are `kind=trend` with `display=stickiness` or `display=lifecycle`. Lists and objects (`filters`, `series`, `steps`, `exclusions`, `breakdowns`, `pathCleaning`) travel as JSON text in the query string, so use `curl -G --data-urlencode`.

HTTP (curl) — Weekly p90 order value by plan, with the previous period:
```bash
curl -G https://apphelm.dev/api/v1/query \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  --data-urlencode productId=prd_… \
  --data-urlencode kind=trend \
  --data-urlencode eventName=order_paid \
  --data-urlencode interval=week \
  --data-urlencode days=180 \
  --data-urlencode math=p90 \
  --data-urlencode mathProperty=amount \
  --data-urlencode breakdown=person:plan \
  --data-urlencode compare=true
```

A three-step funnel with a 7-day window:
```bash
curl -G https://apphelm.dev/api/v1/query \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  --data-urlencode productId=prd_… \
  --data-urlencode kind=funnel \
  --data-urlencode steps=signup_started,signup_completed,order_paid \
  --data-urlencode conversionWindowValue=7 \
  --data-urlencode conversionWindowUnit=day \
  --data-urlencode 'filters=[{"key":"utm_source","operator":"equals","value":"newsletter"}]'
```

Weekly retention of signups returning to order:
```bash
curl -G https://apphelm.dev/api/v1/query \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  --data-urlencode productId=prd_… \
  --data-urlencode kind=retention \
  --data-urlencode firstEvent=signup_completed \
  --data-urlencode returnEvent=order_paid \
  --data-urlencode granularity=week \
  --data-urlencode periods=12
```

A formula: conversion rate as a percentage:
```bash
curl -G https://apphelm.dev/api/v1/query \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  --data-urlencode productId=prd_… \
  --data-urlencode kind=trend \
  --data-urlencode 'series=[{"eventName":"signup_started","math":"people"},{"eventName":"signup_completed","math":"people"}]' \
  --data-urlencode 'formula=B/A*100'
```

The answer is `{ "object": "query_result", "productId", "days", "data" }`, where `data` holds the result for the kind and its `caveat`. Retention answers without `days`, because it reads its own periods.

| Kind | Parameters |
| --- | --- |
| `trend` | `eventName` or `series` (up to 4), `formula`, `interval`, `math`, `mathProperty`, `mathGroupType`, `compare`, `cumulative`, `smoothing` (`7` or `28`), `breakdown`, `breakdowns`, `breakdownLimit`, `display` (`stickiness`, `lifecycle`), `granularity` (lifecycle) |
| `funnel` | `steps` (comma list or JSON array of names and `{ eventName, filters }`), `funnelOrder`, `conversionWindowValue` with `conversionWindowUnit` (or the older `conversionWindowDays`), `exclusions`, `timingFrom`, `timingTo`, `correlation`, `correlationProperties`, `breakdown`, `interval` (conversion over time) |
| `retention` | `firstEvent`, `returnEvent`, `firstFilters`, `returnFilters`, `granularity`, `periods`, `retentionType`, `breakdown`. Refuses `days` |
| `path` | `pathEvents`, `startPoint` (or `startPath`), `endPoint`, `pathSteps`, `pathExclude`, `pathCleaning` |
| `web` | `days` (up to 90). The web analytics report; see [Web analytics and attribution](https://apphelm.dev/docs/web-analytics) |

Every kind takes `filters`, and `days` (default 30) or `dateFrom` with `dateTo`. The [API reference](https://apphelm.dev/docs/api) lists every parameter with its type and limits.

## The SQL API

`POST /api/v1/query/sql` runs one query, with the same tables and limits as the editor. It needs a workspace server key with `analytics:read` (also a default scope), because rows can be single events and people.

HTTP (curl):
```bash
curl https://apphelm.dev/api/v1/query/sql \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","days":90,"query":"SELECT toStartOfWeek(timestamp) AS week, uniq(person_id) AS people FROM events WHERE event = '\''signup_completed'\'' GROUP BY week ORDER BY week"}'
```

Node.js — weekly-signups.ts (plain fetch, no SDK needed):
```ts
const response = await fetch("https://apphelm.dev/api/v1/query/sql", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.APPHELM_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    productId: "prd_…",
    days: 90,
    query: "SELECT toStartOfWeek(timestamp) AS week, uniq(person_id) AS people FROM events WHERE event = 'signup_completed' GROUP BY week ORDER BY week",
  }),
});
const { data } = await response.json(); // data.columns, data.rows, data.hasMore, data.caveat
```

Python — weekly_signups.py (standard library only):
```python
import json, os, urllib.request

body = {
    "productId": "prd_…",
    "days": 90,
    "query": "SELECT toStartOfWeek(timestamp) AS week, uniq(person_id) AS people "
             "FROM events WHERE event = 'signup_completed' GROUP BY week ORDER BY week",
}
request = urllib.request.Request(
    "https://apphelm.dev/api/v1/query/sql",
    data=json.dumps(body).encode(),
    headers={"Authorization": f"Bearer {os.environ['APPHELM_API_KEY']}", "Content-Type": "application/json"},
)
data = json.load(urllib.request.urlopen(request))["data"]  # columns, rows, hasMore, caveat
```

| Field | Notes |
| --- | --- |
| `productId` | Required |
| `query` | Required. One `SELECT` (with `WITH`), at most 20,000 characters |
| `days` | 1–365, default 30 |
| `dateFrom`, `dateTo` | Instead of `days`: whole UTC days, both inclusive. Send both or neither |
| `format` | `json` (default) or `csv`. CSV has a header row, and the `x-apphelm-has-more` header says whether rows were left out |

The JSON answer is `{ "object": "sql_result", "productId", "data": { "columns", "types", "rows", "rowCount", "hasMore", "limit", "clamped", "durationMs", "range", "tables", "caveat" } }`. Each row is an array in column order.

Coding agents can run the same query through the MCP tool `apphelm_run_sql`, list synced tables with `apphelm_list_warehouse_tables`, and read saved insights and dashboards with `apphelm_list_saved_insights`, `apphelm_get_saved_insight`, `apphelm_list_dashboards` and `apphelm_get_dashboard`. See [MCP servers](https://apphelm.dev/docs/mcp).

## Manage insights through the API

Saved insights, dashboards, annotations, alerts and subscriptions all have REST routes. Reading needs `analytics:read`. Every change needs `analytics:write`, which a key never has by default: an owner or admin adds it by name in **Settings → API keys**, because alerts and subscriptions email and notify members. Changes are made in the name of the person who created the key, who must be an owner or admin, and every change needs an `Idempotency-Key` header (a retry with the same key replays the first answer).

```bash
curl https://apphelm.dev/api/v1/saved-insights \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","name":"Weekly signups","kind":"trend","query":{"eventName":"signup_completed","mode":"people","interval":"week","days":90},"tags":["growth"]}'
```

| Route | Does |
| --- | --- |
| `GET /saved-insights?productId=&kind=&tag=&q=&createdBy=` | List saved insights, with tag and creator facets |
| `GET /saved-insights/{id}?run=true` | One saved insight and its query; `run=true` adds its result now |
| `POST /saved-insights` | Save one: `productId`, `name`, `kind` (`trend`, `funnel`, `retention`, `path`, `sql`), `query`, optional `description` and `tags` |
| `PATCH /saved-insights/{id}` | Change `name`, `description`, `tags`, `kind` or `query`; `expectedUpdatedAt` refuses a stale edit with `409 insight_changed` |
| `POST /saved-insights/{id}` | Duplicate it (optional `name`) |
| `DELETE /saved-insights/{id}` | Delete it, with its tiles, alerts, subscriptions and share links |
| `GET /dashboards?productId=`, `GET /dashboards/{id}?run=true` | Dashboards and templates; one dashboard with each tile's result when `run=true` |
| `POST /dashboards` | `name`, `description`, `productId`, `filters`; or `templateKey` (`product_analytics`, `web_analytics`, `performance`) and `productId`, with an optional `conversionEvent` |
| `PATCH /dashboards/{id}` | `name`, `description`, `filters` |
| `POST /dashboards/{id}` | A tile change: `action` = `add_insight` `{ insightId, width? }`, `add_text` `{ body, width? }`, `update_tile`, `remove_tile`, `reorder` `{ tileIds }` or `duplicate` |
| `DELETE /dashboards/{id}` | Delete it; its saved insights stay |
| `GET`, `POST /annotations`; `PATCH`, `DELETE /annotations/{id}` | Chart annotations: `day`, `note`, `productId` |
| `GET`, `POST /insight-alerts`; `GET`, `PATCH`, `DELETE /insight-alerts/{id}` | Alerts; one alert with its last 50 checks. `status: "disabled"` turns one off |
| `GET`, `POST /insight-subscriptions`; `PATCH`, `DELETE /insight-subscriptions/{id}` | Subscriptions to a `saved_insight` or `dashboard`; `status: "paused"` pauses one |
| `GET`, `POST /cohorts`; `GET`, `PATCH`, `DELETE /cohorts/{id}` | Cohorts (`segments:read`); static cohorts are created and changed with `cohorts:write` |

From the CLI, `npx @sansavision/apphelm insights list --product prd_…` lists saved insights (also `--kind`, `--tag`, `--search`), and `insights get sin_… --run` prints one with its result. [CLI reference](https://apphelm.dev/docs/cli) has every command.

> **Two kinds of "insights" in the API:** `GET /api/v1/insights` (scope `insights:read`) is not saved charts. It returns the findings AppHelm detects on its own for the Action Inbox. Saved charts are under `/api/v1/saved-insights`.

## Limits

| What | Limit |
| --- | --- |
| Range of most insights | 90 days |
| Trends and stickiness by hour, week, month | 14, 182 and 365 days |
| Lifecycle | 24 hours, 14 days, 8 weeks or 6 months |
| Retention | 31 days, 26 weeks or 12 months of periods |
| Filters | 5 per insight; 3 per series, funnel step, exclusion and retention event |
| Trend series | 4 (A–D); formula up to 60 characters |
| Breakdowns | 2 at once (trends); 1–25 values kept (default 10); 5 cohorts |
| Funnel | 2–6 steps, 3 exclusions, 90-day window, 100,000 event rows read |
| Paths | 2–10 steps, 10 excluded nodes, 5 cleaning rules |
| One insight's database values | 100; more is refused with `422` and a message saying what to remove |
| Query API | 60 requests a minute per key |
| Saved insights | 10 tags; 12,000 characters of query JSON |
| Dashboards | 20 per workspace; 12 insights and 8 text cards each |
| Alerts | 10 per insight; 100 per workspace; 20 recipients |
| Subscriptions | 10 per insight or dashboard; 100 per workspace; 20 recipients |

SQL has its own limits; see [SQL limits](#sql-limits).

## Best practices

- **Name events for what happened** (`order_paid`, not `click_button_3`) so insights read like sentences. [Events and autocapture](https://apphelm.dev/docs/events) has naming conventions.
- **Identify people on sign-in** so funnels and retention follow them from the anonymous visit to the account. Without it, a person who signs up on a second device counts twice.
- **Choose one outcome event per product** and build the main funnel, retention and alerts on it. Dashboards and experiments then agree on what success is.
- **Use person and cohort filters instead of copying conditions** into every insight. A cohort changes in one place.
- **Prefer insights over SQL for recurring numbers.** Insights are cheaper, can carry alerts, and take dashboard filters. Use SQL for one-off questions, joins with revenue data, and shapes the builder does not have.
- **Filter SQL by event.** `WHERE event = '…'` is counted before the query runs and keeps it inside the scan budget; reading every event over a long range is the usual reason for `sql_over_budget`.
- **Keep keys with `analytics:write` few.** They can email and notify your team. A read-only reporting script needs only the default scopes.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| A chart is all zeros | No events with that name in the range, or a filter matches nothing | Check the event name in **Analytics → Overview**, widen the range, and remove filters one at a time |
| The range is shorter than you chose | Your plan's capture retention is shorter than the range | Read the caveat; events older than retention are deleted. A longer retention needs a plan change |
| Unique people are higher than expected | People were anonymous on some events and never identified | Call `identify` on sign-in on every platform ([Users, people and groups](https://apphelm.dev/docs/identify)) |
| Stickiness shows fewer people than a trend | Stickiness counts identified events only | Expected; identify people to include them |
| `422` "This report covers at most 90 days" | The range is longer than this kind allows | Use a week or month interval for a longer trend, or a custom range inside the limit |
| `422` "Retention reads its own periods" | `days` was sent with `kind=retention` | Remove `days`; use `granularity` and `periods` |
| `422` naming filters or steps to remove | The insight needs more than 100 database values | Use fewer filters, step filters or cohort values |
| `403 workspace_key_required` | The key is not a workspace server key | Create a server key (`ahl_live_…`) in Settings → API keys |
| `403 scope_denied` | The key lacks `metrics:read` (query), `analytics:read` (SQL, saved insights) or `analytics:write` (changes) | Add the scope to the key, or create a new key with it |
| `403 product_scope_denied` | The key is limited to other products | Check the key's products in Settings → API keys |
| `404 not_found` | The product id is wrong, or the product isn't in this workspace | Check the id with `GET /api/v1/products` |
| `429 rate_limit_exceeded` | Over 60 query requests a minute on this key | Wait for `retry-after` (60 seconds) and spread requests out |
| `422 sql_invalid` | A syntax error, an unknown table or column, or a function that is not available | The error gives the line and column and, for missing functions, the alternative |
| `422 sql_over_budget` | The query would scan more than 500,000 rows | Narrow the date range, add `WHERE event = '…'`, or read the table once in `WITH` |
| `422 sql_too_complex` | Too many table reads, values, expressions or `IN` items | Read each table once in `WITH`, and split very large `IN` lists |
| `429 sql_busy` | Another query of the workspace is running | Retry after 5 seconds |
| `429 sql_rate_limited` | 60 SQL runs in the last minute in this workspace | Wait a minute; dashboards and saved insights do not count |
| `504 sql_timeout` | The query took longer than 20 seconds | Narrow the range, filter earlier, or read fewer tables |
| `422 insight_not_alertable` | The alert is on a funnel, retention, path, stickiness, lifecycle or SQL insight | Alert on a trend over time instead |
| `409 dashboard_full`, `alert_limit`, `subscription_limit` | A limit in [Limits](#limits) is reached | Remove a tile, alert or subscription you no longer need |
| `422 recipient_not_member` | A recipient cannot see the insight's product | Choose members with access to that product |
| `409 demo_product_read_only` | You tried to save or change something on the demo product | Use one of your own products |
