Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(insights): complete SQL box plot support (#90851)

Paul D'Ambra1f7ec01cc3f3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f4d20ac65aba..38a85b349f8d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7305,9 +7305,9 @@ snapshots:
scenes-app-insights-side-panel-actions--unsaved-insight--light:
hash: v1.k794b7964.4d578bbdfaa1fc1273607e926b15daaffed027ec89dbfad45179410e7a208f6c.hjlOrgS-_brH3WWYD3R8RwnkJs2dmmiNFToArpB2bUc
scenes-app-insights-sqlboxplot--edit-options--dark:
- hash: v1.k794b7964.70df9d8ffa57acac2d95f47d3298bb62ca009f1f4b556717ee0bbe319ab7754e.VwWfKL8TJDDpSmrV3mWOD0VkvzSnBrYJTFtSRpxlQcw
+ hash: v1.k794b7964.b7f6a30e831a8e3ee470968bdfcf500846c23e4fd292d3843194a8604113a621.9W8O7G_Ee7_RKrL8q1ym7vcL_li6isQGZuKW8mi5H3Q
scenes-app-insights-sqlboxplot--edit-options--light:
- hash: v1.k794b7964.836958043bd3b8203146f802f75a29f5edb8ad4c056a5e2cd01d75a14fa453bb.lDduPTYwYFGPpa1wZHBJEHrKfyxy9jVNMI9-pUQAAjE
+ hash: v1.k794b7964.1e2bac52875555b244a4bedeb50be0b93c91c33650035f92ee8ac94f6862a594.myropj0gWcD4YSrQvAdv9uifX0R_QSphdyEIaVXgwLw
scenes-app-insights-sqlboxplot--grouped-series--dark:
hash: v1.k794b7964.0062f9e095cb6266619d2886be6973be68c7fc906f50d8b37064390de6757656.frURXaRskPxT8wSqipNvLkFVNmgq3uiSKORwD_fLWDA
scenes-app-insights-sqlboxplot--grouped-series--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 21124a353109..6dd7f923c423 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -2286,9 +2286,56 @@
},
"type": "object"
},
+ "AssistantDataVisualizationBoxPlotSettings": {
+ "additionalProperties": false,
+ "properties": {
+ "excludeOutliers": {
+ "description": "Clip whiskers to 1.5 times the interquartile range. Defaults to true.",
+ "type": "boolean"
+ },
+ "maxColumn": {
+ "description": "Numeric column containing the maximum for each box.",
+ "type": "string"
+ },
+ "meanColumn": {
+ "description": "Numeric column containing the mean for each box.",
+ "type": "string"
+ },
+ "medianColumn": {
+ "description": "Numeric column containing the median for each box.",
+ "type": "string"
+ },
+ "minColumn": {
+ "description": "Numeric column containing the minimum for each box.",
+ "type": "string"
+ },
+ "p25Column": {
+ "description": "Numeric column containing the 25th percentile for each box.",
+ "type": "string"
+ },
+ "p75Column": {
+ "description": "Numeric column containing the 75th percentile for each box.",
+ "type": "string"
+ },
+ "seriesColumn": {
+ "description": "Optional column that groups each X-axis value into separate colored series. Set to `null` for one series.",
+ "type": ["string", "null"]
+ },
+ "xAxisColumn": {
+ "description": "X-axis category column. Set to `null` for one overall distribution or one box per series.",
+ "type": ["string", "null"]
+ }
+ },
+ "required": ["minColumn", "p25Column", "medianColumn", "meanColumn", "p75Column", "maxColumn"],
+ "type": "object"
+ },
"AssistantDataVisualizationChartSettings": {
"additionalProperties": false,
"properties": {
+ "boxPlot": {
+ "$ref": "#/definitions/AssistantDataVisualizationBoxPlotSettings",
+ "description": "Column mappings for `BoxPlot`. The SQL must return one pre-aggregated row per X-axis and series pair."
+ },
"goalLines": {
"description": "Horizontal goal lines drawn across the chart.",
"items": {
@@ -2347,7 +2394,7 @@
"type": "object"
},
"AssistantDataVisualizationDisplayType": {
- "description": "Subset of `ChartDisplayType` values supported by `AssistantDataVisualizationNode`.\n\n- `ActionsTable` — render rows as a data table. This is the default when `display` is omitted.\n- `BoldNumber` — big-number display for single-value results (first numeric column of the first row).\n- `ActionsLineGraph` — line chart. Requires at least two columns, including one numeric column.\n- `ActionsBar` — bar chart with one bar per X-axis value.\n- `ActionsPie` — pie chart for categorical proportions. Requires one label column and one numeric column.\n- `ActionsStackedBar` — bar chart stacked by a series breakdown column.\n- `ActionsAreaGraph` — area chart. Requires at least two columns, including one numeric column.\n- `TwoDimensionalHeatmap` — 2D heatmap. Requires an X column, a Y column, and a numeric value column.\n- `ScatterPlot` — scatter plot of one measure against another. Requires two numeric columns, one per axis.",
+ "description": "Subset of `ChartDisplayType` values supported by `AssistantDataVisualizationNode`.\n\n- `ActionsTable` — render rows as a data table. This is the default when `display` is omitted.\n- `BoldNumber` — big-number display for single-value results (first numeric column of the first row).\n- `ActionsLineGraph` — line chart. Requires at least two columns, including one numeric column.\n- `ActionsBar` — bar chart with one bar per X-axis value.\n- `ActionsPie` — pie chart for categorical proportions. Requires one label column and one numeric column.\n- `ActionsStackedBar` — bar chart stacked by a series breakdown column.\n- `ActionsAreaGraph` — area chart. Requires at least two columns, including one numeric column.\n- `TwoDimensionalHeatmap` — 2D heatmap. Requires an X column, a Y column, and a numeric value column.\n- `ScatterPlot` — scatter plot of one measure against another. Requires two numeric columns, one per axis.\n- `BoxPlot` — box plot from pre-aggregated SQL rows. Requires six numeric summary columns.",
"enum": [
"ActionsTable",
"BoldNumber",
@@ -2357,7 +2404,8 @@
"ActionsStackedBar",
"ActionsAreaGraph",
"TwoDimensionalHeatmap",
- "ScatterPlot"
+ "ScatterPlot",
+ "BoxPlot"
],
"type": "string"
},
@@ -2386,7 +2434,7 @@
},
"display": {
"$ref": "#/definitions/AssistantDataVisualizationDisplayType",
- "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Otherwise → `ActionsTable`."
+ "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`."
},
"kind": {
"const": "DataVisualizationNode",
diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.ts
index 54a39e9152dc..adfcfe2e559e 100644
--- a/frontend/src/queries/schema/schema-assistant-queries.ts
+++ b/frontend/src/queries/schema/schema-assistant-queries.ts
@@ -1796,6 +1796,7 @@ export interface AssistantInsightVizNode {
* - `ActionsAreaGraph` — area chart. Requires at least two columns, including one numeric column.
* - `TwoDimensionalHeatmap` — 2D heatmap. Requires an X column, a Y column, and a numeric value column.
* - `ScatterPlot` — scatter plot of one measure against another. Requires two numeric columns, one per axis.
+ * - `BoxPlot` — box plot from pre-aggregated SQL rows. Requires six numeric summary columns.
*/
export type AssistantDataVisualizationDisplayType =
| ChartDisplayType.ActionsTable
@@ -1807,6 +1808,7 @@ export type AssistantDataVisualizationDisplayType =
| ChartDisplayType.ActionsAreaGraph
| ChartDisplayType.TwoDimensionalHeatmap
| ChartDisplayType.ScatterPlot
+ | ChartDisplayType.BoxPlot
export interface AssistantDataVisualizationAxisDisplaySettings {
/** Which Y axis this numeric series should use. Use `right` for a secondary Y axis. */
@@ -1876,6 +1878,27 @@ export interface AssistantDataVisualizationYAxisSettings {
showGridLines?: boolean
}
+export interface AssistantDataVisualizationBoxPlotSettings {
+ /** X-axis category column. Set to `null` for one overall distribution or one box per series. */
+ xAxisColumn?: string | null
+ /** Optional column that groups each X-axis value into separate colored series. Set to `null` for one series. */
+ seriesColumn?: string | null
+ /** Numeric column containing the minimum for each box. */
+ minColumn: string
+ /** Numeric column containing the 25th percentile for each box. */
+ p25Column: string
+ /** Numeric column containing the median for each box. */
+ medianColumn: string
+ /** Numeric column containing the mean for each box. */
+ meanColumn: string
+ /** Numeric column containing the 75th percentile for each box. */
+ p75Column: string
+ /** Numeric column containing the maximum for each box. */
+ maxColumn: string
+ /** Clip whiskers to 1.5 times the interquartile range. Defaults to true. */
+ excludeOutliers?: boolean
+}
+
export interface AssistantDataVisualizationChartSettings {
/**
* Column used as the X axis. Typically a time bucket or categorical column, but `ScatterPlot`
@@ -1890,6 +1913,8 @@ export interface AssistantDataVisualizationChartSettings {
leftYAxisSettings?: AssistantDataVisualizationYAxisSettings
/** Settings for the right Y axis. Only applies when a Y series uses `settings.display.yAxisPosition: "right"`. */
rightYAxisSettings?: AssistantDataVisualizationYAxisSettings
+ /** Column mappings for `BoxPlot`. The SQL must return one pre-aggregated row per X-axis and series pair. */
+ boxPlot?: AssistantDataVisualizationBoxPlotSettings
/**
* Column that splits a single Y series into multiple colored series — e.g. breaking down
* a line chart by `country`. Set to `null` or omit to disable. A breakdown buckets rows by
@@ -1941,6 +1966,7 @@ export interface AssistantDataVisualizationNode {
* - Categorical comparison → `ActionsBar` or `ActionsStackedBar`.
* - Two-dimensional aggregation → `TwoDimensionalHeatmap`.
* - Relationship between two numeric measures, one point per row → `ScatterPlot`.
+ * - Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.
* - Otherwise → `ActionsTable`.
*/
display?: AssistantDataVisualizationDisplayType
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index e5787e5d1286..b4d70433e49c 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -46,6 +46,7 @@ import { LoadPreviewText } from '~/queries/nodes/DataNode/LoadNext'
import { QueryExecutionDetails } from '~/queries/nodes/DataNode/QueryExecutionDetails'
import { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import { PieChart } from '~/queries/nodes/DataVisualization/Components/Charts/PieChart'
+import { SqlBoxPlot } from '~/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot'
import { SqlChart } from '~/queries/nodes/DataVisualization/Components/Charts/SqlChart'
import { SqlScatterGraph } from '~/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph'
import { TwoDimensionalHeatmap } from '~/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap'
@@ -925,6 +926,7 @@ function InternalDataTableVisualization(
responseLoading,
xData,
yData,
+ columns,
chartSettings,
dashboardId,
dataVisualizationProps,
@@ -1003,6 +1005,18 @@ function InternalDataTableVisualization(
presetChartHeight={presetChartHeight}
/>
)
+ } else if (effectiveVisualizationType === ChartDisplayType.BoxPlot) {
+ const rows = ('results' in response ? response.results : 'result' in response ? response.result : []) ?? []
+ component = (
+ <SqlBoxPlot
+ rows={Array.isArray(rows) ? rows : []}
+ columns={columns}
+ chartSettings={chartSettings}
+ analyticsKey={dataVisualizationProps.key}
+ presetChartHeight={presetChartHeight}
+ className="p-2"
+ />
+ )
} else if (effectiveVisualizationType === ChartDisplayType.TwoDimensionalHeatmap) {
component = <TwoDimensionalHeatmap />
} else if (effectiveVisualizationType === ChartDisplayType.BoldNumber) {
diff --git a/frontend/src/scenes/insights/stories/SQLBoxPlot.stories.tsx b/frontend/src/scenes/insights/stories/SQLBoxPlot.stories.tsx
index 87d7ccea29b7..0e53149030ce 100644
--- a/frontend/src/scenes/insights/stories/SQLBoxPlot.stories.tsx
+++ b/frontend/src/scenes/insights/stories/SQLBoxPlot.stories.tsx
@@ -87,6 +87,14 @@ export const EditOptions: Story = {
},
},
play: async ({ canvasElement }): Promise<void> => {
+ await waitFor(
+ () => {
+ if (!canvasElement.querySelector('[data-attr="sql-box-plot"]')) {
+ throw new Error('Box plot not ready')
+ }
+ },
+ { timeout: 10_000 }
+ )
await waitFor(
async () => {
if (canvasElement.querySelector('[data-attr="box-plot-minColumn"]')) {
diff --git a/posthog/schema.py b/posthog/schema.py
index 1df30fdccaf6..afebcae9d73c 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -531,6 +531,32 @@ class AssistantDataVisualizationAxisSettings(BaseModel):
)
+class AssistantDataVisualizationBoxPlotSettings(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ excludeOutliers: bool | None = Field(
+ default=None,
+ description=("Clip whiskers to 1.5 times the interquartile range. Defaults to true."),
+ )
+ maxColumn: str = Field(..., description="Numeric column containing the maximum for each box.")
+ meanColumn: str = Field(..., description="Numeric column containing the mean for each box.")
+ medianColumn: str = Field(..., description="Numeric column containing the median for each box.")
+ minColumn: str = Field(..., description="Numeric column containing the minimum for each box.")
+ p25Column: str = Field(..., description="Numeric column containing the 25th percentile for each box.")
+ p75Column: str = Field(..., description="Numeric column containing the 75th percentile for each box.")
+ seriesColumn: str | None = Field(
+ default=None,
+ description=(
+ "Optional column that groups each X-axis value into separate colored series. Set to `null` for one series."
+ ),
+ )
+ xAxisColumn: str | None = Field(
+ default=None,
+ description=("X-axis category column. Set to `null` for one overall distribution or one box per series."),
+ )
+
+
class AssistantDataVisualizationGoalLine(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -3391,6 +3417,12 @@ class AssistantDataVisualizationChartSettings(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ boxPlot: AssistantDataVisualizationBoxPlotSettings | None = Field(
+ default=None,
+ description=(
+ "Column mappings for `BoxPlot`. The SQL must return one pre-aggregated row per X-axis and series pair."
+ ),
+ )
goalLines: list[AssistantDataVisualizationGoalLine] | None = Field(
default=None, description="Horizontal goal lines drawn across the chart."
)
@@ -9190,7 +9222,8 @@ class AssistantDataVisualizationNode(BaseModel):
" Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n-"
" Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship"
" between two numeric measures, one point per row → `ScatterPlot`.\n-"
- " Otherwise → `ActionsTable`."
+ " Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with"
+ " `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`."
),
)
kind: Literal["DataVisualizationNode"] = "DataVisualizationNode"
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 838823c70cbd..02fc13bdc8b7 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -229,6 +229,7 @@ class AssistantDataVisualizationDisplayType(StrEnum):
ACTIONS_AREA_GRAPH = "ActionsAreaGraph"
TWO_DIMENSIONAL_HEATMAP = "TwoDimensionalHeatmap"
SCATTER_PLOT = "ScatterPlot"
+ BOX_PLOT = "BoxPlot"
class Scale(StrEnum):
diff --git a/products/product_analytics/backend/tests/api/test_insight_query.py b/products/product_analytics/backend/tests/api/test_insight_query.py
index 8705200ce73a..e3cf5f834a29 100644
--- a/products/product_analytics/backend/tests/api/test_insight_query.py
+++ b/products/product_analytics/backend/tests/api/test_insight_query.py
@@ -35,6 +35,33 @@ class TestMCPInsightSerializer(SimpleTestCase):
assert box_plot["xAxisColumn"] is None
assert box_plot["seriesColumn"] is None
+ def test_assistant_schema_accepts_sql_box_plots(self) -> None:
+ query = schema.AssistantDataVisualizationNode.model_validate(
+ {
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": "select 1"},
+ "display": "BoxPlot",
+ "chartSettings": {
+ "boxPlot": {
+ "xAxisColumn": "bucket",
+ "seriesColumn": "series",
+ "minColumn": "min",
+ "p25Column": "p25",
+ "medianColumn": "median",
+ "meanColumn": "mean",
+ "p75Column": "p75",
+ "maxColumn": "max",
+ "excludeOutliers": True,
+ }
+ },
+ }
+ )
+
+ assert query.display == schema.AssistantDataVisualizationDisplayType.BOX_PLOT
+ assert query.chartSettings is not None
+ assert query.chartSettings.boxPlot is not None
+ assert query.chartSettings.boxPlot.medianColumn == "median"
+
class TestInsight(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest, QueryMatchingTest):
maxDiff = None
diff --git a/products/product_analytics/skills/creating-box-plot-insights/SKILL.md b/products/product_analytics/skills/creating-box-plot-insights/SKILL.md
new file mode 100644
index 000000000000..53f1dc6febbe
--- /dev/null
+++ b/products/product_analytics/skills/creating-box-plot-insights/SKILL.md
@@ -0,0 +1,112 @@
+---
+name: creating-box-plot-insights
+description: >-
+ Creates product analytics or SQL-backed box plot insights in PostHog. Use when a user asks to create, build, or save a box plot, visualize a numeric distribution, compare quartiles or medians across dates or groups, or turn SQL results into a box plot. Chooses between a standard Trends box plot and a SQL insight, validates the distribution data, saves the insight, and verifies it.
+---
+
+# Creating box plot insights
+
+Box plots need distribution data, not an already-aggregated average or total. Choose the simplest query type that can express the user's question.
+
+## Choose the query type
+
+Use a **standard product analytics box plot** when all of these are true:
+
+- The source is an event, action, or warehouse table supported by Trends.
+- One numeric property contains the values to distribute.
+- The user wants the distribution over a normal time interval.
+
+Use a **SQL box plot** when the user needs custom grouping, joins, derived values, or bespoke SQL. Read `querying-posthog-data` before writing HogQL, then use [references/sql-examples.md](references/sql-examples.md) as a starting point.
+
+Do not use SQL only to reproduce a standard Trends query.
+
+## Standard product analytics box plot
+
+1. Identify the event or action and its numeric property. Confirm the property is numeric before saving.
+2. Build an `InsightVizNode` whose source is a `TrendsQuery`:
+ - Set the series event or action.
+ - Set `math_property` to the numeric property.
+ - Set `trendsFilter.display` to `BoxPlot`.
+ - Choose the date range and interval that match the question.
+3. Run the query with `posthog:query-trends`.
+4. If it returns distribution rows, save it with `posthog:insight-create`.
+5. Read it back with `posthog:insight-get` and confirm the property, interval, and display.
+
+A box plot without a numeric `math_property` is invalid. Do not substitute event counts unless counts are the values the user wants to distribute.
+
+## SQL box plot
+
+The SQL must return one pre-aggregated row for each X-axis and series pair. Calculate the summary in the database. Never calculate percentiles from the limited result rows in the client.
+
+Required numeric roles:
+
+- minimum
+- 25th percentile
+- median
+- mean
+- 75th percentile
+- maximum
+
+The easiest result shape uses these aliases:
+
+```text
+x, series, min, p25, median, mean, p75, max
+```
+
+`x` and `series` are optional:
+
+- Set `xAxisColumn` to `null` for one overall distribution or one box per series.
+- Set `seriesColumn` to `null` for one series.
+
+Validate the HogQL with `posthog:execute-sql` before saving. Check that:
+
+- Every required statistic is numeric.
+- `min <= p25 <= median <= p75 <= max` for every row.
+- The mean is between the minimum and maximum.
+- Each X-axis and series pair appears once.
+- There are at most 200 series and 10,000 X-axis by series cells.
+
+Then save this shape with `posthog:insight-create`:
+
+```json
+{
+ "query": {
+ "kind": "DataVisualizationNode",
+ "source": {
+ "kind": "HogQLQuery",
+ "query": "<validated HogQL>"
+ },
+ "display": "BoxPlot",
+ "chartSettings": {
+ "boxPlot": {
+ "xAxisColumn": "x",
+ "seriesColumn": "series",
+ "minColumn": "min",
+ "p25Column": "p25",
+ "medianColumn": "median",
+ "meanColumn": "mean",
+ "p75Column": "p75",
+ "maxColumn": "max",
+ "excludeOutliers": true
+ }
+ }
+ }
+}
+```
+
+Use the actual aliases when the query uses different names. Do not map the six statistics as six Y-axis series.
+
+## Verify the saved insight
+
+1. Read the saved insight with `posthog:insight-get`.
+2. Run it with `posthog:insight-query`.
+3. Confirm the result still has the expected columns and one row per box.
+4. Report the insight link, the numeric value being distributed, and the grouping choices.
+
+If an individual row has a missing or invalid summary, PostHog omits that box while keeping valid boxes visible. Fix the SQL when omitted boxes are not expected.
+
+## Related skills
+
+- `querying-posthog-data` - required before authoring or changing the HogQL for a SQL box plot.
+- `formatting-insight-axes` - use when the value axis needs currency, duration, percentage, or other formatting.
+- `building-a-dashboard` - use when the box plot should be placed with other insights on a dashboard.
diff --git a/products/product_analytics/skills/creating-box-plot-insights/references/sql-examples.md b/products/product_analytics/skills/creating-box-plot-insights/references/sql-examples.md
new file mode 100644
index 000000000000..3d2a841c4164
--- /dev/null
+++ b/products/product_analytics/skills/creating-box-plot-insights/references/sql-examples.md
@@ -0,0 +1,108 @@
+# SQL box plot examples
+
+Run each query with `posthog:execute-sql` before using it in an insight.
+
+## Deterministic sample data
+
+Use this query to test the full SQL box plot flow without relying on project event properties:
+
+```sql
+SELECT
+ bucket AS x,
+ series,
+ min(value) AS min,
+ quantile(0.25)(value) AS p25,
+ quantile(0.5)(value) AS median,
+ avg(value) AS mean,
+ quantile(0.75)(value) AS p75,
+ max(value) AS max
+FROM (
+ SELECT
+ concat('Week ', toString(modulo(number, 4) + 1)) AS bucket,
+ if(modulo(intDiv(number, 4), 2) = 0, 'Free', 'Paid') AS series,
+ toFloat(
+ modulo(number * 37, 100)
+ + if(modulo(intDiv(number, 4), 2) = 0, 0, 20)
+ ) AS value
+ FROM numbers(1000)
+)
+GROUP BY bucket, series
+ORDER BY bucket, series
+```
+
+Map `xAxisColumn` to `x` and `seriesColumn` to `series`.
+
+## Event property over time
+
+Replace the event, property, and series expression with values from the user's project:
+
+```sql
+SELECT
+ toStartOfWeek(timestamp) AS x,
+ properties.plan AS series,
+ min(toFloat(properties.latency_ms)) AS min,
+ quantile(0.25)(toFloat(properties.latency_ms)) AS p25,
+ quantile(0.5)(toFloat(properties.latency_ms)) AS median,
+ avg(toFloat(properties.latency_ms)) AS mean,
+ quantile(0.75)(toFloat(properties.latency_ms)) AS p75,
+ max(toFloat(properties.latency_ms)) AS max
+FROM events
+WHERE
+ event = 'request completed'
+ AND timestamp >= now() - INTERVAL 8 WEEK
+ AND properties.latency_ms IS NOT NULL
+GROUP BY x, series
+ORDER BY x, series
+```
+
+Use `toFloatOrNull` instead of `toFloat` when the property can contain non-numeric strings, then filter null values in an inner query before aggregating.
+
+## One overall distribution
+
+Return one row and set both grouping fields to `null`:
+
+```sql
+SELECT
+ min(toFloat(properties.latency_ms)) AS min,
+ quantile(0.25)(toFloat(properties.latency_ms)) AS p25,
+ quantile(0.5)(toFloat(properties.latency_ms)) AS median,
+ avg(toFloat(properties.latency_ms)) AS mean,
+ quantile(0.75)(toFloat(properties.latency_ms)) AS p75,
+ max(toFloat(properties.latency_ms)) AS max
+FROM events
+WHERE
+ event = 'request completed'
+ AND timestamp >= now() - INTERVAL 30 DAY
+ AND properties.latency_ms IS NOT NULL
+```
+
+Use:
+
+```json
+{
+ "xAxisColumn": null,
+ "seriesColumn": null
+}
+```
+
+## One box per series, without an X-axis
+
+Return one row per series and set only `xAxisColumn` to `null`:
+
+```sql
+SELECT
+ properties.plan AS series,
+ min(toFloat(properties.latency_ms)) AS min,
+ quantile(0.25)(toFloat(properties.latency_ms)) AS p25,
+ quantile(0.5)(toFloat(properties.latency_ms)) AS median,
+ avg(toFloat(properties.latency_ms)) AS mean,
+ quantile(0.75)(toFloat(properties.latency_ms)) AS p75,
+ max(toFloat(properties.latency_ms)) AS max
+FROM events
+WHERE
+ event = 'request completed'
+ AND timestamp >= now() - INTERVAL 30 DAY
+ AND properties.latency_ms IS NOT NULL
+GROUP BY series
+ORDER BY series
+```
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index ed957a0bdd96..d9a611e074e6 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -36,6 +36,31 @@ const AssistantInsightVizNode = z.object({
),
})
+const AssistantDataVisualizationBoxPlotSettings = z.object({
+ excludeOutliers: z.coerce
+ .boolean()
+ .describe('Clip whiskers to 1.5 times the interquartile range. Defaults to true.')
+ .optional(),
+ maxColumn: z.string().describe('Numeric column containing the maximum for each box.'),
+ meanColumn: z.string().describe('Numeric column containing the mean for each box.'),
+ medianColumn: z.string().describe('Numeric column containing the median for each box.'),
+ minColumn: z.string().describe('Numeric column containing the minimum for each box.'),
+ p25Column: z.string().describe('Numeric column containing the 25th percentile for each box.'),
+ p75Column: z.string().describe('Numeric column containing the 75th percentile for each box.'),
+ seriesColumn: z
+ .string()
+ .nullable()
+ .describe(
+ 'Optional column that groups each X-axis value into separate colored series. Set to `null` for one series.'
+ )
+ .optional(),
+ xAxisColumn: z
+ .string()
+ .nullable()
+ .describe('X-axis category column. Set to `null` for one overall distribution or one box per series.')
+ .optional(),
+})
+
const AssistantDataVisualizationGoalLine = z.object({
label: z.string().describe('Label rendered next to the goal line.'),
value: z.coerce.number().describe('Y-axis value at which the goal line is drawn.'),
@@ -105,6 +130,9 @@ const AssistantDataVisualizationAxis = z.object({
})
const AssistantDataVisualizationChartSettings = z.object({
+ boxPlot: AssistantDataVisualizationBoxPlotSettings.describe(
+ 'Column mappings for `BoxPlot`. The SQL must return one pre-aggregated row per X-axis and series pair.'
+ ).optional(),
goalLines: z
.array(AssistantDataVisualizationGoalLine)
.describe('Horizontal goal lines drawn across the chart.')
@@ -154,6 +182,7 @@ const AssistantDataVisualizationDisplayType = z.enum([
'ActionsAreaGraph',
'TwoDimensionalHeatmap',
'ScatterPlot',
+ 'BoxPlot',
])
const AssistantDataVisualizationTableSettings = z.object({
@@ -170,7 +199,7 @@ const AssistantDataVisualizationNode = z.object({
'Chart configuration. Ignored when `display` is `ActionsTable` or `BoldNumber`.'
).optional(),
display: AssistantDataVisualizationDisplayType.describe(
- 'Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Otherwise → `ActionsTable`.'
+ 'Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`.'
).optional(),
kind: z.literal('DataVisualizationNode').default('DataVisualizationNode'),
source: z.record(z.string(), z.unknown()).describe('HogQL query object that produces the rows to visualize.'),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
index 43a428c6570f..c7c768fe2a9e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
@@ -60,6 +60,70 @@
"chartSettings": {
"description": "Chart configuration. Ignored when `display` is `ActionsTable` or `BoldNumber`.",
"properties": {
+ "boxPlot": {
+ "description": "Column mappings for `BoxPlot`. The SQL must return one pre-aggregated row per X-axis and series pair.",
+ "properties": {
+ "excludeOutliers": {
+ "description": "Clip whiskers to 1.5 times the interquartile range. Defaults to true.",
+ "type": "boolean"
+ },
+ "maxColumn": {
+ "description": "Numeric column containing the maximum for each box.",
+ "type": "string"
+ },
+ "meanColumn": {
+ "description": "Numeric column containing the mean for each box.",
+ "type": "string"
+ },
+ "medianColumn": {
+ "description": "Numeric column containing the median for each box.",
+ "type": "string"
+ },
+ "minColumn": {
+ "description": "Numeric column containing the minimum for each box.",
+ "type": "string"
+ },
+ "p25Column": {
+ "description": "Numeric column containing the 25th percentile for each box.",
+ "type": "string"
+ },
+ "p75Column": {
+ "description": "Numeric column containing the 75th percentile for each box.",
+ "type": "string"
+ },
+ "seriesColumn": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional column that groups each X-axis value into separate colored series. Set to `null` for one series."
+ },
+ "xAxisColumn": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "X-axis category column. Set to `null` for one overall distribution or one box per series."
+ }
+ },
+ "required": [
+ "maxColumn",
+ "meanColumn",
+ "medianColumn",
+ "minColumn",
+ "p25Column",
+ "p75Column"
+ ],
+ "type": "object"
+ },
"goalLines": {
"description": "Horizontal goal lines drawn across the chart.",
"items": {
@@ -310,7 +374,7 @@
"type": "object"
},
"display": {
- "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Otherwise → `ActionsTable`.",
+ "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`.",
"enum": [
"ActionsTable",
"BoldNumber",
@@ -320,7 +384,8 @@
"ActionsStackedBar",
"ActionsAreaGraph",
"TwoDimensionalHeatmap",
- "ScatterPlot"
+ "ScatterPlot",
+ "BoxPlot"
],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
index 17e256cb7381..3688797e8a1a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
@@ -71,6 +71,70 @@
"chartSettings": {
"description": "Chart configuration. Ignored when `display` is `ActionsTable` or `BoldNumber`.",
"properties": {
+ "boxPlot": {
+ "description": "Column mappings for `BoxPlot`. The SQL must return one pre-aggregated row per X-axis and series pair.",
+ "properties": {
+ "excludeOutliers": {
+ "description": "Clip whiskers to 1.5 times the interquartile range. Defaults to true.",
+ "type": "boolean"
+ },
+ "maxColumn": {
+ "description": "Numeric column containing the maximum for each box.",
+ "type": "string"
+ },
+ "meanColumn": {
+ "description": "Numeric column containing the mean for each box.",
+ "type": "string"
+ },
+ "medianColumn": {
+ "description": "Numeric column containing the median for each box.",
+ "type": "string"
+ },
+ "minColumn": {
+ "description": "Numeric column containing the minimum for each box.",
+ "type": "string"
+ },
+ "p25Column": {
+ "description": "Numeric column containing the 25th percentile for each box.",
+ "type": "string"
+ },
+ "p75Column": {
+ "description": "Numeric column containing the 75th percentile for each box.",
+ "type": "string"
+ },
+ "seriesColumn": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional column that groups each X-axis value into separate colored series. Set to `null` for one series."
+ },
+ "xAxisColumn": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "X-axis category column. Set to `null` for one overall distribution or one box per series."
+ }
+ },
+ "required": [
+ "maxColumn",
+ "meanColumn",
+ "medianColumn",
+ "minColumn",
+ "p25Column",
+ "p75Column"
+ ],
+ "type": "object"
+ },
"goalLines": {
"description": "Horizontal goal lines drawn across the chart.",
"items": {
@@ -321,7 +385,7 @@
"type": "object"
},
"display": {
- "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Otherwise → `ActionsTable`.",
+ "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Categorical proportions → `ActionsPie`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`.",
"enum": [
"ActionsTable",
"BoldNumber",
@@ -331,7 +395,8 @@
"ActionsStackedBar",
"ActionsAreaGraph",
"TwoDimensionalHeatmap",
- "ScatterPlot"
+ "ScatterPlot",
+ "BoxPlot"
],
"type": "string"
},