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

# Multi-step queries

> Combine explores and transform results server-side with DuckDB and Python in AI agents and MCP

[Beta](https://docs.lightdash.com/support/feature-badges.md#beta)

A multi-step query runs a sequence of queries and transformations on the Lightdash server and returns only the final result. An AI agent or [Lightdash MCP](https://docs.lightdash.com/agents/lightdash-mcp.md) client pulls governed metrics from one or more explores, then joins, reshapes, aggregates, or runs Python over those results in one request. Intermediate rows stay on the server, so they never fill the context window, and you don't need to install DuckDB or Python locally.

Use multi-step queries when a question goes beyond what a single explore query can express, even when your explores are already joined and you don't have SQL Runner access:

* **Combine separate data sources.** Join explores that have no dbt join between them, or join a warehouse explore with a [live source](https://docs.lightdash.com/integrations/live-sources) or an [attached CSV](https://docs.lightdash.com/agents/use-ai-agents.md#attach-a-file).
* **Reshape or re-aggregate governed results.** Answer questions like *"how many orders were above that customer's own average, by status?"*, which compares each order to its customer's average before regrouping by status. You can also compute a 7-day rolling average of daily signups that counts days with zero signups. A single explore query omits empty days, so DuckDB builds a date spine and joins the governed metric onto it.
* **Run statistics and models in Python.** Fit a trend line, forecast, regression, or anomaly score over governed query results.

In each case, the source steps remain governed semantic-layer queries. DuckDB or Python performs only the final join, reshape, or calculation on the Lightdash server.

![Lineage dependency graph showing Weekly orders and Weekly payments semantic-layer steps joined in DuckDB and passed to a Python four-week forecast step marked Final result](https://mintcdn.com/lightdash/5kvdElwoOR5KAwdC/images/agents/multi-step-queries/lineage-overview.png?fit=max\&auto=format\&n=5kvdElwoOR5KAwdC\&q=85\&s=80a28bd492a65c611e89aa2cc7c3850f)

Two semantic-layer explores joined in DuckDB and passed to a four-week Python forecast

## Before you start

Multi-step queries are on by default on Lightdash Cloud. On a self-hosted instance, enable the `compose-sql-runner` feature flag, configure results storage, and add a Python sandbox if you want Python steps. See [Post-processing with DuckDB and Python](https://docs.lightdash.com/self-host/enterprise-features/ai-agents.md#post-processing-with-duckdb-and-python).

* **Lightdash AI agents.** Turn multi-step queries on or off per agent in the [agent's settings](https://docs.lightdash.com/agents/set-up-agents.md#composer-queries-optional). The setting is on by default once the feature is enabled, and the agent needs [data access](https://docs.lightdash.com/agents/data-access.md) that lets it read result rows.
* **Lightdash MCP.** Multi-step queries are available whenever your role holds `manage:Explore`, which Interactive Viewer, Editor, Developer, and Admin roles include. If you [pin an agent](https://docs.lightdash.com/agents/lightdash-mcp.md#pin-an-agent-with-the-x-lightdash-agent-header), that agent must also have multi-step queries turned on.
* **Warehouse SQL steps.** Running raw SQL against your warehouse requires `manage:SqlRunner`, which Developer and Admin roles include by default. In Lightdash AI agents, warehouse SQL steps also require [SQL mode](https://docs.lightdash.com/agents/use-ai-agents.md#sql-mode) and query approval. DuckDB and Python steps over semantic-layer results require neither SQL Runner access nor approval.

## Why run transformations in Lightdash

Without multi-step queries, complex questions fail in two ways. Either the AI client runs several separate queries and dumps thousands of raw rows into its context window to join by hand, or it falls back to raw warehouse SQL and bypasses your semantic layer.

Multi-step queries run the whole workflow on the Lightdash server:

* **Keep queries on your semantic layer.** Agents pull governed metrics from explores first, then apply window functions, rankings, ratios, and cross-explore joins in DuckDB instead of writing raw warehouse SQL. Your dbt metric definitions, joins, and user attributes apply to every source step.
* **Keep the context window small.** Four explores might produce thousands of intermediate rows while the joined and ranked answer is ten rows. Lightdash runs the intermediate steps on the server and returns only the final result. The model never truncates intermediate rows or does the arithmetic by hand.
* **No local tools to install.** Non-coding clients such as Claude Desktop, Slack, and the Lightdash app get DuckDB and Python execution over one connection, with no local Python environment, packages, or DuckDB binary to set up.
* **One server-side call over MCP.** One request to [Lightdash MCP](https://docs.lightdash.com/agents/lightdash-mcp.md) runs your semantic-layer queries and DuckDB or Python post-processing together on the server, instead of pulling raw tables into a local script or chat window.

## Run multi-step queries over Lightdash MCP

Connect an MCP client, such as Claude Desktop or Cursor, to [Lightdash MCP](https://docs.lightdash.com/agents/lightdash-mcp.md) and ask cross-explore or analytical questions in plain language. Your MCP client plans the steps, sends them to Lightdash in a single request, and receives only the final result table instead of every intermediate query's rows.

For full tool arguments and schema details, see [Query pipelines in Lightdash MCP](https://docs.lightdash.com/agents/lightdash-mcp.md#query-pipelines).

> [accordion] Example MCP pipeline payload
>
> ```json theme={null}
> {
>   "projectUuid": "<project-uuid>",
>   "queries": [
>     {
>       "sourceType": "semanticLayer",
>       "nodeId": "orders_mo",
>       "title": "Monthly orders",
>       "description": "Total order amount and unique order count by order month.",
>       "exploreName": "orders",
>       "dimensions": ["orders_order_date_month"],
>       "metrics": ["orders_total_order_amount", "orders_unique_order_count"]
>     },
>     {
>       "sourceType": "semanticLayer",
>       "nodeId": "payments_mo",
>       "title": "Monthly payments",
>       "description": "Total payment revenue and payment count by order month.",
>       "exploreName": "payments",
>       "dimensions": ["orders_order_date_month"],
>       "metrics": ["payments_total_revenue", "payments_unique_payment_count"]
>     },
>     {
>       "sourceType": "duckdb",
>       "nodeId": "combined_mo",
>       "title": "Combined monthly with cumulative revenue",
>       "description": "Joins orders and payments by month and computes cumulative revenue.",
>       "references": ["orders_mo", "payments_mo"],
>       "sql": "SELECT COALESCE(o.orders_order_date_month, p.orders_order_date_month) AS month, o.orders_total_order_amount AS order_amount, p.payments_total_revenue AS payment_revenue, SUM(COALESCE(p.payments_total_revenue, 0)) OVER (ORDER BY COALESCE(o.orders_order_date_month, p.orders_order_date_month)) AS cumulative_revenue FROM orders_mo AS o FULL OUTER JOIN payments_mo AS p ON o.orders_order_date_month = p.orders_order_date_month ORDER BY month"
>     },
>     {
>       "sourceType": "python",
>       "nodeId": "trend_fit",
>       "title": "Order amount linear trend",
>       "description": "Fits a least-squares linear trend line to monthly order amount.",
>       "references": ["combined_mo"],
>       "code": "import numpy as np\nimport pandas as pd\ndef run(inputs, params):\n    df = inputs[\"combined_mo\"].sort_values(\"month\").reset_index(drop=True)\n    x = np.arange(len(df), dtype=float)\n    y = pd.to_numeric(df[\"order_amount\"], errors=\"coerce\")\n    mask = y.notna()\n    slope, intercept = np.polyfit(x[mask], y[mask], 1)\n    return df.assign(trend_line=slope * x + intercept)"
>     }
>   ]
> }
> ```

## Inspect lineage in AI agents

When a [Lightdash AI agent](https://docs.lightdash.com/agents/use-ai-agents.md) answers with a multi-step query, the result panel opens with a **Chart** and **Lineage** toggle in its top-right corner.

Switch to **Lineage** to audit every step:

* **Dependency graph.** Each node shows its title, kind, and row count, and **Final result** marks the output. Select any node in the graph to jump to its detail card.
* **Step cards.** Semantic-layer cards show the explore, selected dimensions, metrics, filters, and a toggle between the metric query and compiled SQL, plus **Explore from here** to open that source in Explore. DuckDB and Python cards show their SQL or code, execution time, and upstream references.
* **Intermediate rows.** Expand the row-count bar on any step to inspect the exact table that step produced.
* **Add to chat.** Pin any intermediate step to the message input to ask follow-up questions over it without rebuilding earlier steps.

Opening a multi-step result runs its steps with the viewer's permissions, so viewers only see data they can access. In the **Quick actions** (`···`) menu, **Download results** exports the final table as CSV and **Export image** downloads chart results as an image. Both actions require `manage:ExportCsv`, which Viewer roles and above include.

## How multi-step queries run

Every multi-step query runs in two layers on the Lightdash server:

| Layer | What it runs | Where it runs |
| - | - | - |
| **Sources** | Governed semantic-layer explores, [live sources](https://docs.lightdash.com/integrations/live-sources), [attached CSVs](https://docs.lightdash.com/agents/use-ai-agents.md#attach-a-file), [external sources](https://docs.lightdash.com/explore/external-sources.md), or warehouse SQL when allowed | Your warehouse through the semantic layer, or inside Lightdash |
| **Transformations** | DuckDB for joins, unions, window functions, rankings, and re-aggregation; Python for statistics, trend lines, and forecasts | Isolated DuckDB sessions and ephemeral Python sandboxes inside Lightdash |

1. **Sources run first.** Semantic-layer queries compile through your semantic layer and run against your warehouse, or match a [pre-aggregate](https://docs.lightdash.com/semantic-layer/pre-aggregates) or [results cache](https://docs.lightdash.com/semantic-layer/caching.md) entry. Warehouse SQL runs only when allowed and needed.
2. **DuckDB and Python transform the results inside Lightdash.** Each transformation reads only the results of its upstream steps and never connects to your warehouse. Same-grain explore joins preserve governed field labels and formatting, and apply the same fan-out protection as [Merge queries](https://docs.lightdash.com/explore/merge-queries.md#how-the-join-stays-honest).
3. **Only the final result returns to the client.** Intermediate rows stay on the server.

## Run Python inside Lightdash

For forecasts, trend lines, regressions, or statistical calculations that SQL expresses poorly, Lightdash runs Python in an isolated sandbox created for each run and destroyed afterward.

The sandbox has no network access, no warehouse credentials, and no runtime package installs. It receives only the upstream query results it transforms, and comes preinstalled with `pandas`, `numpy`, `scipy`, `pyarrow`, `scikit-learn`, and `polars`. You can visualize Python outputs with built-in chart types or a custom chart from [Chart Studio](https://docs.lightdash.com/visualizations/chart-studio.md).

![Weekly revenue forecast rendered with a custom chart from Chart Studio, showing weekly order bars, cumulative payments, an OLS trend line, a shaded four-week forecast horizon, and a 95% prediction interval](https://mintcdn.com/lightdash/w-cdnqMINuDUnHkR/images/agents/multi-step-queries/lineage-python.png?fit=max\&auto=format\&n=w-cdnqMINuDUnHkR\&q=85\&s=fbba9fd8f5716dc81355dce0603213d9)

A four-week Python OLS forecast with a 95% prediction interval over weekly orders and payments, rendered with a custom chart from Chart Studio

## Save as a chart

[Beta](https://docs.lightdash.com/support/feature-badges.md#beta)

> [!NOTE]
>
> Saving multi-step queries as charts is gated by the `composer-charts` feature flag, which is off by default. [Contact Lightdash support](mailto:support@lightdash.com) to enable it on Lightdash Cloud, or add `composer-charts` to `LIGHTDASH_ENABLE_FEATURE_FLAGS` on a self-hosted instance.

Save a multi-step query from an AI agent or Lightdash MCP to a space or onto a dashboard. Teammates can then open, refresh, and share it without returning to the chat.

* **Save and edit through AI agents or MCP.** Open **Quick actions** (`···`) and choose **Save** in an AI agent thread, or ask an AI agent or MCP client to save or update the chart in a space or dashboard.
* **Works with the rest of Lightdash.** Multi-step charts support [content-as-code](https://docs.lightdash.com/workflow/content-as-code.md), project [promotion](https://docs.lightdash.com/explore/promote-content.md), spaces, dashboards, dashboard filters, parameters, date zoom, and dashboard scheduled deliveries and exports.

![Chart view in an AI agent thread showing weekly order revenue, an OLS forecast, and cumulative payments, with the Quick actions menu open to Download results and Save](https://mintcdn.com/lightdash/5kvdElwoOR5KAwdC/images/agents/multi-step-queries/chart-save-menu.png?fit=max\&auto=format\&n=5kvdElwoOR5KAwdC\&q=85\&s=10b24ba774a4b8764cf3e1b5859c8a1b)

Open Quick actions in the result panel to download results or save the multi-step query to a space or dashboard

A multi-step chart saved to a space opens on its own page with a **Chart** card, a collapsible **Lineage** card, and a **Parameters** card when any source step references project or model parameters. From the header you can refresh the query, export CSV or image data, add the chart to a dashboard, rename, move, or delete it, or click **Ask AI** to edit it in chat.

![Saved multi-step chart page showing the weekly orders and payments combo forecast chart at top and the expanded Lineage card with the four-step graph and source explore cards below](https://mintcdn.com/lightdash/5kvdElwoOR5KAwdC/images/agents/multi-step-queries/saved-chart-page.png?fit=max\&auto=format\&n=5kvdElwoOR5KAwdC\&q=85\&s=00a7b6512a36076b1c8bea059709ff15)

A saved multi-step chart page showing the rendered chart above its full Lineage graph and step details

### Permissions for saving charts

Viewing a multi-step chart or dashboard tile uses the same space and dashboard view permissions as any other chart. Saving or editing one requires `manage:ComposerChart`, which Editor, Developer, and Admin roles include, plus the scope for any step type in the query:

| Query includes | Additional scope required | System roles that include it |
| - | - | - |
| DuckDB, Python, or merge step | `manage:Explore` | Interactive Viewer, Editor, Developer, Admin |
| Same-grain explore merge | `manage:MergeQuery` | Developer, Admin |
| Warehouse SQL step | `manage:SqlRunner` | Developer, Admin |
| Custom SQL dimensions or SQL custom metrics | `manage:CustomFields` | Developer, Admin |
| SQL table calculations | `manage:CustomSqlTableCalculations` | Developer, Admin |

## Current limits

| Area | Today |
| - | - |
| Steps and rows | Each request supports up to 25 steps and 500 rows per step by default, or up to 5,000 rows per step when requested. Downstream DuckDB and Python steps only see the rows upstream steps returned, so source queries aggregate before hitting the limit. |
| DuckDB and Python resources | DuckDB runs with 512 MB memory and 2 threads per query by default; self-hosted instances can adjust this with `PRE_AGGREGATE_DUCKDB_QUERY_MEMORY_LIMIT`. Python steps have a 5-minute timeout, a 64 MB maximum output size, fixed preinstalled libraries, and no network access or runtime package installs. |
| Editing saved charts | Multi-step charts have no manual visual query editor. Update them through **Ask AI**, Lightdash MCP, or [content-as-code](https://docs.lightdash.com/workflow/content-as-code.md). |
| Content validation and Autopilot | [Content validation](https://docs.lightdash.com/workflow/validating-your-content.md) and [Autopilot](https://docs.lightdash.com/agents/autopilot.md) don't check or repair multi-step charts yet. |
| Embedded dashboards | Embedded dashboards show a placeholder for multi-step chart tiles, and require `@lightdash/sdk` 3.245.0 or newer when a dashboard contains one. |
| Deliveries and alerts | Dashboard scheduled deliveries and exports include multi-step chart tiles. Multi-step charts don't support standalone chart deliveries or [alerts](https://docs.lightdash.com/explore/create-alerts.md) yet. |
| Attached CSVs and live sources | Multi-step queries that read an attached CSV can't be saved as charts. Each live source step is bounded by its integration's per-query row limit. |


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