Query
Run read-only ClickHouse SQL over one Observe project's spans, traces, sessions, users, eval results and annotations, then chart, save or download results.
About
Query is a tab in each Observe project that runs read-only ClickHouse SQL over that project’s data. You select from a catalog of seven datasets: spans, traces, sessions, users, eval_results, derived_metrics and annotations. The server rewrites every dataset you name so it only returns rows from the current project and the time window you pick. You can’t name other tables, databases or table functions, and a query can’t change data: only one SELECT statement is accepted, and the connection runs read-only.
Your organization role and your workspace role both count, and the lower of the two applies:
| Role | What you can do |
|---|---|
| Viewer | Open the catalog, examples and saved queries; run, estimate and cancel queries (including saved ones); see your history; download your results |
| Member or above | Everything a Viewer can do, plus save queries, update or delete your own saved queries, and add a shared saved query to a dashboard |
Organization Admins and Owners have access even without a workspace membership. A project that is not an Observe project shows Project not available.
On a self-hosted deployment, runs fail with Configure the dedicated read-only SQL connection first. until the dedicated read-only ClickHouse connection is set up.
When to use
- Break down spans by model, provider, status or a span attribute, such as
attrs_string['key']. - Compute latency percentiles or an error rate per UTC day.
- Join spans with sessions, users, eval results or annotations, for example to compare human annotations with evaluator scores.
- Download a result as CSV or Parquet for a spreadsheet or data tool.
- Put a saved query on a dashboard, where it reruns for each viewer.
Use the Explore dashboard to browse projects and the trace table without writing SQL.
Example: cost and tokens by model
Open the Examples tab in the left panel.

Choose Cost and tokens by model. The example replaces the editor text as a new, unsaved query; choose Undo in the confirmation if you want your previous text back.
The example query is:
SELECT model,
count() AS span_count,
sum(total_tokens) AS tokens,
round(sum(cost), 6) AS total_cost
FROM spans
GROUP BY model
ORDER BY total_cost DESC, model
You don’t add a project or time filter yourself. With the default Last 1 day window, spans already holds only this project’s spans that started in the last 24 hours. Choose Run query. The result has one row per model with its span count, total tokens and total cost, most expensive first. A model with no spans in the window doesn’t appear. Spans that don’t call a model, such as tool spans, are grouped under an empty model; add WHERE model != '' to hide them.
To see it as a chart, choose Chart, then set Category to model and Value to total_cost. The chart is titled total_cost by model.
How to
Open the Query tab
Open an Observe project and choose Query in the tab row: Trace, Sessions, Users, Query, Insights.
The header shows Read-only ClickHouse SQL · Project scoped and the run limits: 30 s timeout · 10,000-row limit · 8 MB result limit. The banner below it warns that datasets use raw storage identifiers: merged session and user identities are not consolidated, so joins and distinct counts can differ from the Observe views after an identity merge.

Find datasets and columns
The left panel has three tabs, Catalog, Examples and Saved, and a search box that filters the open tab.
- Catalog lists each dataset with its description, columns and ClickHouse types. Select a column, or choose Insert dataset, to insert its backtick-quoted name at the cursor. A dataset that isn’t available in the project shows the reason.
- Examples lists 12 vetted queries. Choosing one replaces the editor text. An example that needs an unavailable dataset is disabled. Examples go through the same checks and project scope as SQL you type.
- Saved lists saved queries. Search filters the current page of 20 only; use Previous and Next to page. See Saved queries.
Write the query
The editor starts with:
SELECT model, count() AS spans, sum(total_tokens) AS tokens
FROM spans
GROUP BY model
ORDER BY spans DESCSuggestions appear as you type, after . or a backtick, or when you press Ctrl+Space. They cover datasets, columns with their types, keywords and a few common functions; the full list of allowed functions is in Functions. Refer to datasets by their catalog name, such as spans, and read span attributes with attrs_string['key'] or attrs_number['key']. See SQL you can write for what the checker accepts.
Pick a time window
Choose Last hour, Last 1 day (the default), Last 7 days or Last 31 days. The window is computed when you run the query, ending at that moment. Each dataset is filtered on its own time column; see Datasets. You can add more conditions in WHERE, but you can’t read outside the window.
Check the estimate
Shortly after you stop typing, the line under the editor shows an advisory scan estimate, for example Estimate: spans ≤ N rows (M index granules) · within the 10,000,000-row scan limit. It never blocks a run.
| Estimate line | Meaning |
|---|---|
| Estimate: likely over the 10,000,000-row scan limit. | Narrow the time window or filter the query before you run it. |
| This query will be rejected: followed by a reason | The query fails validation. Fix it before running. |
| not estimated (shared index) next to a dataset, and the line ends with scan limit not checked | That dataset’s index is shared across projects, so no row count is shown and the query isn’t compared with the scan limit. |
| Estimate paused: too many estimates. Run is not affected. | You passed 30 estimates per minute. |
| Estimate unavailable. Run is not affected. | The estimate couldn’t be computed. The run works normally. |
The estimate can be unavailable on a deployment where the estimator isn’t set up. Treat it as a hint, not a guarantee.
Run or cancel
Choose Run query, or press ⌘+Enter (Mac) or Ctrl+Enter in the editor. The status moves through queued and running to succeeded, failed or cancelled.
- Choose Cancel query to stop a run. A queued run is cancelled at once; a running scan is cancelled in the database.
- While your query is queued or running, Run query is unavailable. Wait for it to finish or choose Cancel query first.
- Leaving the tab doesn’t cancel the query on the server.
- You can have one active query at a time, and an organization two. Otherwise the tab shows A query is already running. Cancel it or wait for completion.
- If the tab can’t reach the server for 120 seconds, it stops checking and shows Query status unavailable. Polling stopped; the server query was not cancelled. Run again to retry. If you lose access to the query, it stops at once with This query is no longer accessible. Check your project access, then run again. The query keeps running on the server until it finishes or reaches its time limit.
Read the results
Table is the default view. Each column header shows the column name and its ClickHouse type. NULL and an empty string are shown differently. The table shows 50 rows per page, and the line above it reads rows, columns and run time, such as 3 rows · 5 columns · 78 ms.
Chart draws a bar chart. Pick a Category (any column) and a Value (a numeric column); the chart is titled with both, such as calls by model. It plots only the first 50 rows. Chart is disabled when the result has no numeric column.

Results from before you changed the SQL or window are labelled Previous until you run again. An empty result says No rows in this window. Try a wider window or check your filters.
Download the result
Choose Download, then CSV (opens in spreadsheets) or Parquet (for data tools). The file is query-results.csv or query-results.parquet and holds the same rows as the result, so at most 10,000. CSV is UTF-8 with a byte order mark. In CSV, text cells that start with =, +, -, @, a tab or a carriage return (ignoring leading spaces) get a leading ' so spreadsheets don’t run them as formulas. Parquet uses snappy compression; column types are inferred from the values, so dates, UUIDs and very large integers are stored as text.
Download works only for a succeeded result that hasn’t expired.
Saved queries
Choose Save query and enter a Query name (up to 160 characters) and a Visibility:
| Visibility | Who can open it |
|---|---|
| Private | Only you |
| Project members | Anyone in this project. Each person runs it with their own access; results are never shared. |
A saved query keeps its SQL, its time window and its view (table, or chart with its category and value). The Saved tab lists your own queries and those shared with the project, 20 per page, each marked Private or Shared with project with its window.
- Opening a saved query and running it unchanged reruns the stored SQL with a fresh access check. If you edit it, it is marked Edited and runs as an ad-hoc query.
- Only the owner can update or delete a saved query. When you save a query you own, the dialog is titled Update saved query and saving replaces it, including its name, for everyone who can open it. You can’t save a copy of your own query. To delete one, open it and choose Delete saved query.
- If you save someone else’s shared query, a new copy is created.
- Deleting a saved query stops any dashboard widgets that use it.
- Copy query link, available on project-shared queries, copies the tab’s address with
?saved=and the query’s id.
History
Choose History to open your last 20 runs in this project. Each entry shows its state, time, SQL and any error, and is marked results expired once its result is gone. Select an entry to open it in the editor. History shows only your own runs.
Add to a dashboard
Add to dashboard is enabled when all of these are true:
- You are a Member or above.
- The open query is saved and shared with Project members.
- The editor SQL matches the saved SQL.
Choose a dashboard in the same workspace. This adds a widget named after the saved query, using its saved table or chart view. The widget stores a reference to the saved query, not your result: every viewer’s widget runs the query again with that viewer’s permissions.
The widget uses the dashboard’s date range when one is set, otherwise the saved window ending now. It reruns when the date range changes or when you choose Refresh on the dashboard. A range over 31 days shows an error instead of running. Each SQL widget uses the viewer’s one active-query slot and counts toward their daily query limit, so several SQL widgets load one after another. While another query holds the slot, the widget shows Waiting for a query slot for up to 90 seconds. Editing the widget opens the saved query in the Query tab.
Query from an MCP client
The Future AGI MCP server exposes four read tools for the same queries: get_sql_catalog, run_sql, get_sql_result and cancel_sql. run_sql takes the project, the SQL and a time window of at most 31 days, and returns a job id. get_sql_result returns up to 100 rows per page (fewer when rows are wide); pass next_offset as offset until has_more is false. Long cell values are shortened in these pages; for full values, run the query in the Query tab and download the result. There are no MCP tools for estimates, saved queries, history, downloads or dashboards.
Datasets
| Dataset | One row per | Window column | Notes |
|---|---|---|---|
spans | Live span | start_time | No prompt or output payloads |
traces | Live trace | created_at | |
sessions | Session first seen in the window | first_seen | locale is the latest span locale in the window |
users | User first seen in the window | first_seen | Not a count of active users |
eval_results | Live eval score for the project’s eval configs | created_at | Scores from deleted configs stay, with config_deleted = 1. Unavailable for projects with more than 1,000 eval configs, including deleted ones. |
derived_metrics | Committed derived-metric attempt | window_start, window_end | Only metric windows fully inside the selected window. Listed as unavailable when the deployment hasn’t enabled derived metrics. |
annotations | Annotation score (filter score_source = 'human' for human labels) | created_at | Legacy annotations without project ownership are excluded |
spans has 17 columns: id, trace_id, session_id, raw_session_id, user_id, raw_user_id, name, start_time, end_time, latency_ms, status, model, provider, total_tokens, cost, attrs_string (a string-to-string map) and attrs_number (a string-to-number map).
Other columns you’ll use often:
| Dataset | Columns |
|---|---|
traces | id, session_id, raw_session_id, name, external_id, created_at, metadata |
sessions | id, raw_id, external_id, first_seen, locale |
users | id, raw_id, external_id (your own user id), user_id_type, first_seen, metadata |
eval_results | id, trace_id, span_id, session_id, config_id, target_type, score, passed, label, error, created_at, eval_task_id, sampling fields such as inclusion_probability, and config_deleted |
annotations | id, trace_id, span_id, session_id, label_id, value, notes, created_at, score_source |
derived_metrics | 32 columns, including metric_id, metric_version, rollup, group_key, value, numerator, denominator, status, window_start, window_end, std_error, ci_low, ci_high and ci_status |
eval_results.run_id is always NULL for now. In derived_metrics, std_error, ci_low and ci_high (the 95% interval) are set only when ci_status is ok; otherwise ci_reason says why there is no interval. The Catalog tab lists every column with its type.
Joining on ids
spans.id and spans.trace_id are String, while traces.id and trace_id in eval_results and annotations are UUID. Comparing them directly fails with a type error. Because an ON condition can only compare columns, convert the UUID side in a CTE or subquery first, as the Sampled vs. all spans by model example does:
WITH e AS (
SELECT span_id, toString(trace_id) AS target_trace_id, score
FROM eval_results
)
SELECT s.model AS model, avg(e.score) AS avg_score
FROM spans AS s
INNER JOIN e ON s.id = e.span_id AND s.trace_id = e.target_trace_id
GROUP BY s.model
SQL you can write
A query is one ClickHouse SELECT. You can combine SELECTs with UNION ALL; a bare UNION is rejected. It can use:
WHERE,GROUP BY,HAVING,ORDER BY,LIMIT,OFFSETandDISTINCTCASE,if,CAST,BETWEEN,LIKE,ILIKE,INTERVAL, andINwith a subquery or a list of constants- Subqueries and non-recursive CTEs (
WITH name AS (SELECT ...)) - Map access, such as
attrs_string['key'] INNERandLEFTjoins, and window functions with an inlineOVER (...)
Each ON condition must compare columns from two different table aliases with =, joined by AND. USING also works. Unmatched columns from a join are NULL. This join comes from the Sessions per user example:
SELECT s.user_id AS user_id,
u.external_id AS external_user_id,
count(DISTINCT s.session_id) AS session_count,
count() AS span_count
FROM spans AS s
LEFT JOIN users AS u ON s.user_id = u.id
WHERE s.user_id IS NOT NULL
GROUP BY s.user_id, u.external_id
ORDER BY session_count DESC, span_count DESC, s.user_id
LIMIT 100
users holds only users first seen in the window, so external_user_id is filled only for those users; it is NULL for returning users.
Functions
Only approved functions run. Anything else fails with Function X is not in the approved catalog.
| Kind | Functions |
|---|---|
| Aggregates | count, countIf, sum, sumIf, avg, avgIf, min, minIf, max, maxIf, any, anyLast, argMin, argMax, uniq, uniqIf, uniqExact, uniqExactIf, uniqCombined, median, quantile, quantiles, quantileExact, quantileTDigest, stddevPop, stddevSamp, varPop, varSamp, corr, avgWeighted, groupArray, groupUniqArray, topK |
| Math | abs, round, floor, ceil, ceiling, sqrt, pow, power, log, ln, exp, greatest, least, intDiv, modulo |
| Conditionals and nulls | coalesce, ifNull, nullIf, if, multiIf |
| Strings, arrays and maps | lower, upper, length, lengthUTF8, substring, concat, trim, ltrim, rtrim, replace, replaceAll, position, positionCaseInsensitive, startsWith, endsWith, match, splitByChar, splitByString, arrayElement, has, mapKeys, mapValues, mapContains |
| JSON | JSONExtract, JSONExtractString, JSONExtractFloat, JSONExtractInt, JSONExtractUInt, JSONExtractBool, JSONExtractRaw, JSONExtractKeys, JSONHas, JSONLength, JSONType |
| Types and dates | toString, toUUID, toUUIDOrNull, toInt64, toFloat64, toDate, toDateTime, toDateTime64, toStartOfMinute, toStartOfFiveMinutes, toStartOfFifteenMinutes, toStartOfInterval, toStartOfHour, toStartOfDay, toStartOfWeek, toStartOfMonth, toYear, toMonth, toDayOfMonth, toDayOfWeek, toHour, toMinute, formatDateTime, dateDiff, dateAdd, now |
| Window | row_number, rank, dense_rank, ntile, percent_rank, cume_dist, lag, lead, first_value, last_value, plus sum, avg, count, min and max over a window |
groupArrayandgroupUniqArrayneed a size, such asgroupArray(100)(model), of at most 1,000.topKtakes an optional size from 1 to 1,000, such astopK(10)(model).- Quantile levels must be number literals from 0 to 1, with at most 32 levels.
- Ranking functions,
lagandleadcan’t take aROWSorRANGEframe. Frame offsets are at most 1,000,000.lagandleadreturnNULLoutside the partition unless you pass a default value. - Named windows,
DISTINCTinside a window aggregate, and nested windows are not allowed.
Not allowed
| Construct | Message |
|---|---|
More than one statement, or anything other than SELECT | Only a single SELECT or UNION query is allowed. |
SETTINGS, FORMAT, SAMPLE, INTO | Settings, output formats, sampling and statement modifiers are not allowed. |
| Table functions or database-qualified tables | Only unqualified catalog tables are allowed; table functions are forbidden. |
| A name that isn’t a catalog dataset | Unknown dataset: X. |
CROSS, ARRAY, GLOBAL or NATURAL joins, joins without ON or USING, GLOBAL IN, a table name on the right of IN | Rejected before the query runs |
Recursive CTEs, scalar WITH aliases, database-qualified columns | Rejected before the query runs |
| Other SQL constructs | SQL construct X is not supported. |
A query can be at most 32 KiB of SQL, must refer to datasets between 1 and 16 times, and can’t exceed the parser’s complexity limit (The query is too complex.).
Errors and hints
When the database rejects a query, the error names the problem and, where it appears in your own SQL, the offending name.
| Problem | Hint |
|---|---|
| Unknown column or alias | Check its spelling against the dataset columns in the catalog |
| Column not available at that point | Select it in the subquery or CTE first |
| Unknown function | Use a function from Functions |
| Wrong argument type | Convert it with toString() or toFloat64() |
| Syntax error | Check for typos, missing commas and unbalanced parentheses or quotes |
| Wrong number of arguments | Check the function’s arguments |
| Incompatible types compared or combined | Convert one side, for example with toString() or toFloat64(); see Joining on ids |
| Column not in an aggregate | Add it to GROUP BY, or wrap it in an aggregate such as count(), sum() or avg() |
Aggregate nested or in WHERE | Use HAVING or a subquery |
Timeout, memory, rows read, join size or IN set over the limit | Narrow the window or simplify the query. |
| SQL service is busy. Try again shortly. | Run again shortly |
| Query audit submission limit reached for the last 24 hours. | You or your organization reached the daily query count. Wait for older runs to age out. |
| Result storage budget reached for the last 24 hours. Retry after older results expire. | Results from the last 24 hours plus 8 MB per active query exceed the storage budget. Wait for older results to expire. |
| Your role does not allow this action. | Your organization or workspace role is too low for this action, such as saving as a Viewer |
| Only the query owner can edit it. Save a copy instead. | Save someone else’s query as a new copy |
| Share this query with the project before adding it to a dashboard. | Save the query with Project members visibility |
| Result exceeds 8 MB. Aggregate or narrow the query. | Return fewer or smaller rows |
| These results expired. Run the query again. | The result is older than 24 hours; run again |
| Query deadline expired. Run the query again. | Run the query again |
| Metric source data changed or expired. Run the query again. | Data behind a derived_metrics result was removed; run again |
| Query failed. Check the query and try again. | Any other failure |
Limits and interpretation
| Limit | Value |
|---|---|
| Run time | 30 seconds |
| Result rows | 10,000; extra rows are dropped with a warning |
| Result size | 8 MB; a larger result fails the run |
| Output columns | 100 uniquely named columns |
| Data read | 10 million rows or 1 GB |
| Memory | 256 MiB |
IN sets and joins | 1 million rows or 64 MiB |
| Time window | 31 days |
| Active queries | 1 per person, 2 per organization |
| Queries per 24 hours | 1,500 per person, 30,000 per organization (defaults) |
| Result storage per 24 hours | 128 MiB per person, 512 MiB per organization (defaults) |
| Result lifetime | 24 hours |
- A result over 10,000 rows shows Showing the first 10,000 rows. Downloads hold the same rows, so aggregate or narrow the query for a complete answer.
- Results are personal. Only the person who ran a query can open its result, and sharing a saved query never shares a result.
- Datasets use raw session and user ids. After an identity merge, joins and distinct counts can differ from the Observe views.
- The window is applied to each dataset’s own time column, from start (included) to end (excluded), in UTC.
derived_metricskeeps metric windows that start at or after the window start and end at or before the window end.sessionsanduserscontain only those first seen in the window, so they don’t count everyone active in it. sessions,usersandeval_resultscan reach the 10 million-row read limit even in a short window, because their identity or target history isn’t ordered by time. Filter or aggregate instead of only narrowing the window.toDate()and similar functions group by UTC days, which may not match your local day.- A dataset marked unavailable in the catalog can’t be queried in that project, and examples that need it are disabled.
Next steps
Questions & Discussion