# Query Execution (Trino)

Ask a data question in plain English and watch Studio translate it into optimized Trino SQL, execute it against your account, and render the results — all within the chat stream. Full SQL visibility means you can verify every query before acting on the results.

Note
The AI uses the `tdx query` command inside the sandbox execution environment to run Trino queries. Every generated SQL statement is visible in the tool call expansion, so you can review, copy, and re-run it independently.

## Objective

Execute Trino queries against your Treasure AI account through natural-language requests and receive structured, readable results inline in the conversation.

## Prerequisites

- Signed in to Treasure AI Studio ([Getting Started](/products/ai-studio/getting-started))
- At least one database accessible in your Treasure AI account


## Querying Through the AI

The simplest way to query data is to describe what you want in plain language:

- "Show me the top 10 customers by revenue in the last 30 days"
- "How many rows are in the `pageviews` table?"
- "What columns does `mydb.users` have?"


The AI translates your request into a Trino SQL query, executes it using `tdx query`, and presents the results in a formatted table — all within the chat stream.

### What Happens Under the Hood

1. **You describe your query** in natural language
2. **The AI writes SQL** and executes it via the Bash tool: `tdx query "SELECT ..."`
3. **The tool call appears** in the chat showing the command being executed
4. **Query results render** automatically as a structured table (see [Query Result Tables](/products/ai-studio/query/query-results))
5. **The AI interprets** the results and continues the conversation


You can watch each step happen in real time. The tool call indicator shows the running command, and the result table auto-expands when results arrive.

## Requesting Specific Commands

For precise control over query syntax and execution, ask the AI to run the exact command you want:


```
You: Run tdx query "SELECT count(*) AS total_users FROM mydb.users"
```

Or ask it to use `tdx describe` and `tdx show` for quick schema exploration:


```
You: Describe the mydb.users table
You: Show me a preview of mydb.users
```

| Command | Purpose | Output |
|  --- | --- | --- |
| `tdx query "<sql>"` | Execute arbitrary Trino SQL | Query result table |
| `tdx describe <db.table>` | Show table schema (column names and types) | Schema table |
| `tdx show <db.table>` | Preview table data (SELECT * with default limit) | Data table |


See [TDX Commands](/products/ai-studio/query/tdx-commands) for the full command reference.

## Query Lifecycle in the Chat

When a query executes, you see a **tool call indicator** in the chat stream:

### While Running

- A **spinning loader** icon indicates the query is in progress
- The **command description** appears with the full command preview below in monospace
- You can see exactly what SQL is being executed


### On Completion

- A **green checkmark** replaces the spinner
- The tool call row becomes **expandable** — click to see the full command and raw output
- A **query result table** renders automatically below the tool call, showing structured results with column headers, types, and formatted data
- **Execution stats** appear below the table (see [Query Result Tables](/products/ai-studio/query/query-results) for details)
- **Duration badge** shows execution time if 1 second or longer (e.g., "3.2s")


### On Error

- A **red X** icon indicates the query failed
- A **"Query failed"** error card displays with:
  - The SQL that was executed (in monospace)
  - The error message from the query engine
  - The **Job ID** for troubleshooting
- If the tool exited with a non-zero status, an **Exit code badge** (e.g., "Exit 1") appears


## Stopping a Query

If a query is running as part of the AI's response, click the **Stop** button (square icon) in the chat input area to interrupt the AI's execution stream.

Note
Stopping the response terminates the AI's execution stream. The query itself may continue running on the Trino engine. Use the Treasure AI console to cancel long-running queries if needed.

## Query Detection

Studio automatically detects query results from Bash tool calls. The UI recognizes commands containing:

- `tdx query`, `tdx describe`, `tdx show`
- `trino`, `presto`
- `psql`, `mysql`, `sqlite3`


When detected, the raw output is parsed into a structured table rather than displayed as plain text. Two output formats are recognized:

| Format | Description |
|  --- | --- |
| **JSON array** | `[{"col1": val1, ...}, ...]` — produced by `--json` flag |
| **Box-drawing table** | Unicode table format with `┌─│├┤┘` characters — the default `tdx query` output |


Technical Note
Query detection happens client-side via the `detectQueryResult()` function, which inspects the Bash command string and output format. If a Bash tool call matches a query command pattern and its output contains valid JSON arrays or box-drawing table characters, the output renders as a `QueryResultTable` component instead of plain text. The table auto-expands when results are detected during streaming.

## Using Skills for Query Optimization

For complex queries, activate the built-in SQL skills in your project settings to reduce latency and improve efficiency:

| Skill | What It Does |
|  --- | --- |
| `sql-skills:trino` | Write Trino SQL with Treasure AI best practices |
| `sql-skills:hive` | Write Hive SQL for heavy workloads |
| `sql-skills:time-filtering` | Apply `td_interval` and partition pruning for time-based queries |
| `sql-skills:trino-optimizer` | Analyze and optimize slow Trino queries |
| `sql-skills:trino-to-hive-migration` | Convert memory-heavy Trino queries to Hive |


Example: With the `sql-skills:trino-optimizer` skill active, ask the AI to analyze your query for latency bottlenecks. It suggests partition pruning, predicate pushdown, and other optimizations.

See [Skills & Marketplace](/products/ai-studio/skills/skills) for the full skills catalog.

## Best Practices

1. **Start with natural language.** Let the AI write the first draft of your query. Review the SQL in the tool call before interpreting results.
2. **Use `tdx describe` before querying.** Understanding the schema (column names, types) helps both you and the AI write accurate queries.
3. **Set a database context.** Ask the AI to run `tdx use database mydb` at the start of a session to avoid typing fully qualified table names in every query.
4. **Review generated SQL.** The AI writes SQL based on your description and the schema it discovers. Always review the query in the tool call expansion before acting on the results.
5. **Use output format flags for large results.** When you need to process large result sets, ask the AI to use `--json` for structured output or `--output results.csv` to save results to a file.


## Verification

- [ ] Ask "How many rows are in [your_database].[your_table]?" and see a tool call execute `tdx query`
- [ ] See the result rendered as a structured table with column headers and types
- [ ] Expand the tool call to see the full SQL and raw output


## Troubleshooting

| Issue | Solution |
|  --- | --- |
| Query takes too long | Use the `sql-skills:trino-optimizer` skill to analyze for latency issues. Common causes: full table scans (add partition pruning), excessive JOINs, or missing WHERE clauses on time columns |
| Query fails with "access denied" | Verify your Treasure AI account has access to the database and table. Ask the AI to run `tdx databases` to check available databases |
| AI writes incorrect SQL | Activate the `sql-skills:trino` skill before your query request. This gives the AI Treasure AI-specific SQL patterns and functions |


## Next Steps

- [Query Result Tables](/products/ai-studio/query/query-results) — Formatting, column types, and stats
- [TDX Commands](/products/ai-studio/query/tdx-commands) — Full CLI command reference
- [Skills & Marketplace](/products/ai-studio/skills/skills) — SQL skills for optimization and best practices