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

# Query Builder

**Query Builder** is a code-first workspace for writing, running, and saving queries against your connected data sources. Unlike Ask Analysts — which answers questions in natural language — Query Builder gives you direct control over the query itself, with a full code editor, schema-aware autocomplete, AI tab completion, and a conversational assistant that can write or fix queries on demand.

Results render instantly as a table, chart, or KPI. Queries can be saved, reused, and pinned directly to any dashboard.

# The Query Builder Home

Navigate to **Query Builder** in the sidebar to see all saved queries in your workspace.

## Display modes

Toggle between **Card** and **List** view. Your preference is saved.

**List view columns:**

| Column         | Description                                                  |
| -------------- | ------------------------------------------------------------ |
| **Name**       | Query title                                                  |
| **Resource**   | Icons of the databases and tables this query runs against    |
| **Created By** | Who wrote the query — stamped automatically at creation time |
| **Created On** | Date the query was saved                                     |
| **Actions**    | Rename and Delete                                            |

## Search

Filter queries by title using the search bar — fuzzy matching is supported.

Click any query to open it in the editor.

# Creating a Query

Click **New Query** to open the **Create New Query** modal.

| Field                     | Required           | Notes                                                                             |
| ------------------------- | ------------------ | --------------------------------------------------------------------------------- |
| **Enter Query Name**      | Yes                | A descriptive title — shown in the home list and when pinned to dashboards        |
| **Select Data Source**    | Yes (at least one) | The connections this query runs against. Inactive connections cannot be selected. |
| **Select Query Language** | Yes                | The language you'll write in (see below)                                          |

## Query languages

| Language                  | When to use                                                                                                                                                                                                             |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Native Query Language** | SQL (PostgreSQL, MySQL, Redshift, and so on) or your database's own query syntax. Auto-detected from the connected data source. For MongoDB this means aggregation pipelines — see [MongoDB queries](#mongodb-queries). |
| **Python**                | Query one or more data sources, transform data, or combine results across databases. Requires the Python runner feature — see [Python and multi-source queries](#python-and-multi-source-queries).                      |

Once created, the editor opens immediately.

# The Editor

The editor is a split-pane workspace with a right rail:

* **Top pane** — the code editor
* **Bottom pane** — results as a table, chart, or KPI
* **Right rail** — **Schema** and **Assistant** tabs

Drag the divider to resize the panes. Before your first run the editor takes almost the whole height; after a successful run the results pane sizes itself to the number of rows returned, between 15% and 50% of the height.

## The editor header

| Control                      | What it does                                            |
| ---------------------------- | ------------------------------------------------------- |
| **←**                        | Back to the Query Builder home                          |
| Query title                  | The current query's name                                |
| **You have unsaved changes** | Appears whenever the editor has edits you haven't saved |
| **Editor settings** (gear)   | See [Editor settings](#editor-settings)                 |
| Right-rail button            | Reopens the Schema/Assistant rail if you've closed it   |

## Running and saving

These are two separate actions:

| Button        | Shortcut            | Behaviour                                  |
| ------------- | ------------------- | ------------------------------------------ |
| **Save**      | `⌘S` / `Ctrl+S`     | Only appears when you have unsaved changes |
| **Run Query** | `⌘↵` / `Ctrl+Enter` | Runs the query **and** saves it            |

## Code editor features

**Syntax highlighting** for SQL, Python, and the other supported languages.

**Placeholder** — when the editor is empty it reads *"Start typing or ✨ Generate with Query Assistant"*. For languages with a starter snippet it reads *"Start with `<snippet>` or ✨ Generate with Query Assistant"* — the snippet is clickable and seeds the editor with it.

# Autocomplete

Two different systems work side by side.

## Schema autocomplete

As you type, suggestions appear grouped into labelled sections, ranked by relevance:

| Section       | What it contains                                                                                                                       |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| **Keywords**  | SQL keywords and common functions — `SELECT`, `GROUP BY`, `OVER`, `PARTITION BY`, `DATE_TRUNC`, `COALESCE`, `ROW_NUMBER`, and the rest |
| **In query**  | Symbols you defined further up in this query — CTEs, table aliases, column aliases                                                     |
| **Databases** | Databases from your connected data sources                                                                                             |
| **Tables**    | Tables within those databases                                                                                                          |
| **Columns**   | Actual column names and types, fetched from your connections                                                                           |

Ranking is cursor-aware: tables in the database you're currently querying are boosted above the rest. After typing a `.` the list switches to bare names and drops keywords entirely.

## AI tab completion

Beyond the suggestion list, the editor offers whole-completion **ghost text** — a greyed-out continuation of the line you're writing, generated by AI from your schema, your SQL dialect, and the code on both sides of your cursor.

| Key                 | Action                      |
| ------------------- | --------------------------- |
| `Tab`               | Accept the whole suggestion |
| `⌘Tab` / `Ctrl+Tab` | Accept one word             |
| `Escape`            | Dismiss                     |

Typing along with a suggestion advances the ghost text rather than requesting a new one, so it stays out of your way while you type. Ten SQL dialects are supported, plus a dedicated Python path.

> Tab completion can be switched off in **Editor settings → Tab Completion** if you'd rather use `Tab` for indentation.

# Editor Settings

Click the gear (**Editor settings**) in the editor header.

| Setting                    | Notes                                                                      |
| -------------------------- | -------------------------------------------------------------------------- |
| **Title**                  | Rename the query inline, without leaving the editor                        |
| **Vim Mode**               | Vim keybindings in the editor. A mode badge appears in the header when on. |
| **Relative Line Numbers**  | Only shown while Vim Mode is on                                            |
| **Highlight Current Line** | Only shown while Vim Mode is on                                            |
| **Tab Completion**         | Turns [AI tab completion](#ai-tab-completion) on or off                    |
| **Theme**                  | Editor colour scheme (below)                                               |

## Themes

**System** · **Midnight** · **Daylight** · **VS Code Dark+** · **VS Code Light+** · **Dracula** · **Monokai**

**System** follows your Supaboard light/dark setting.

# Viewing Results

Results appear in the bottom pane. Switch format with the tabs above them.

## Table

A paginated, scrollable grid.

* Default page size: 50 rows
* Column headers with data-type metadata
* Export to **CSV**
* Pin to a dashboard as a Table widget

## Chart

An interactive visualisation.

* 28 chart types: bar, column, 100% bar, 100% column, line, area, pie, donut, scatter, grouped scatter, bubble, stacked bar, stacked column, grouped bar, heatmap, treemap, funnel, grouped funnel, gauge, radar, waterfall, sankey, sunburst, map, combo, and more
* Click **Edit** to change chart type, colours, axes, and legend
* Theme-aware colours (adjusts for light/dark automatically)
* Pin to a dashboard as a Chart widget

> The picker only offers chart types your current result shape can actually render, so you will usually see fewer than 28 tiles. Return two measures and grouped variants appear; return one and they don't.

## KPI

A single computed metric.

| Display style  | Description                                        |
| -------------- | -------------------------------------------------- |
| **Numeric**    | A large formatted number — e.g. *1,234,567*        |
| **Percentage** | A value expressed as a percentage — e.g. *85%*     |
| **Trend**      | A value with a directional indicator — e.g. *+12%* |

Pin to a dashboard as a KPI widget.

# Query Assistant

The **Assistant** tab in the right rail is a chat panel that reads your connected schemas and the code currently in the editor, then writes or fixes queries for you. The rail opens automatically the first time you open a query; if you close it, reopen it from the editor header.

## What it does

Type a request in plain English:

* *"Show me the top 10 customers by revenue in the last 90 days"*
* *"Add a filter for status = 'active'"*
* *"Rewrite this to group by month instead of day"*
* *"This query is slow — can you optimise it?"*

It also answers questions without touching your code. Asking *"what does this CTE do?"* gets an explanation, not an edit — the assistant routes your intent to writing, fixing, explaining, or summarising as appropriate.

## Reviewing changes

When the assistant modifies your query the editor switches to **diff mode**, showing your original alongside the suggestion.

* **Per-hunk** — accept or reject each changed block individually
* **All at once** — a floating bar reads *"Accept all changes?"* with **Reject all** (`⌘N` / `Ctrl+N`) and **Accept** (`⌘Y` / `Ctrl+Y`)

A single reply can propose **several** separate changes; those appear as a carousel you can page through. Both sides are formatted before diffing, so you see real hunks rather than one giant block.

You cannot type in the editor until every hunk is resolved — the assistant's input reads *"Accept or reject the change to continue…"* while a diff is open.

## Error fixing

When a query fails, the error appears in the results pane with a **"Fix this error with AI"** button. Clicking it sends the error to the assistant, which diagnoses it and suggests corrected code.

## Conversations

Assistant conversations are **saved**. The header of the assistant panel is a session switcher:

* **New conversation** starts a fresh thread
* **Recent** lists your previous threads for this query — unnamed ones show as *"Untitled session"*

Each turn carries the recent history forward, so follow-ups like *"now do the same for last quarter"* work as expected. Sessions persist across page reloads and across visits.

# Schema Browser

The **Schema** tab in the right rail shows the structure of every data source available to this query.

## What you can browse

* **Data sources** — expandable list of connected databases
* **Tables** — expand any database to see its tables
* **Columns** — expand any table to see its columns

## Search

Filter by resource, table, or column name using the search bar in the panel.

The schema browser reflects the same tables and columns used by autocomplete in the editor — use it as a reference while writing. After you refresh a table's schema from Data Sources, the change applies here and in autocomplete **immediately**; there is no cache to wait out.

# MongoDB Queries

For MongoDB data sources, the assistant writes real **aggregation pipelines** — a JSON array of stages, not a query string.

Two things worth knowing:

* **Read-only.** Generated pipelines never use `$out` or `$merge`.
* **Dates must be Extended JSON.** A date compared as a plain string silently matches **zero** documents rather than erroring. Generated pipelines use the `{"$date": ...}` form; if you hand-edit one, keep it.

Mongo pipelines are validated by actually running them before the assistant shows you the result.

# Python and Multi-Source Queries

> **Feature-gated.** Python and multi-source selection require the Python runner feature. Without it, the language dropdown disables Python and the data-source picker caps you at one source. See [pricing](https://supaboard.ai/pricing).

## Python as the query language

Write Python instead of SQL when you need to:

* Transform or reshape data after retrieval
* Combine results from multiple sources with logic that's awkward in SQL
* Run calculations that are difficult to express in SQL

The editor loads a full Python language mode, and tab completion switches to a Python-aware model.

### The runtime contract

Python queries run in a constrained sandbox, and generated code follows the same rules:

| Rule            | Detail                                                                                                                |
| --------------- | --------------------------------------------------------------------------------------------------------------------- |
| **Connection**  | A single `Connection` object is provided                                                                              |
| **Querying**    | `conn.run(...)` returns a list of dicts                                                                               |
| **Allowed**     | `numpy`                                                                                                               |
| **Not allowed** | `try` / `except` / `finally`; Pydantic, Query or Data classes; direct database drivers such as `pymongo` or `asyncpg` |

Python snippets are not execution-validated before they are shown to you, so run them yourself before saving.

## Multi-source queries

Select more than one data source when creating a query. Multi-source is **Python only** — Python is the glue that joins or merges data across separate databases.

# Pinning Results to a Dashboard

Any result — table, chart, or KPI — can be pinned directly from the results pane.

Click **Pin to Dashboard** above the results, then select an existing dashboard or create one inline. The widget is added immediately and re-runs the underlying query on every dashboard load.

Pinned widgets keep their full configuration — query code, data source mapping, chart type, KPI display style — so they stay accurate as your data changes.

# Managing Saved Queries

## Rename

Either from the Query Builder home — action menu (three dots) → **Rename** — or inline from **Editor settings → Title** while the query is open.

## Delete

Action menu → **Delete**. A confirmation is required. Deleting a query does not remove dashboard widgets pinned from it — those keep working independently.

## Returning to a query

Click any query from the home list. The last saved code, output format, and assistant conversations are all restored.

# Permissions

Access to Query Builder is controlled by the **Query Builder** feature flag on each user's workspace membership. Users without it cannot open Query Builder — see [Workspace — Feature Access](./workspace#feature-access).

| Action                                | Minimum role                            |
| ------------------------------------- | --------------------------------------- |
| View saved queries                    | Viewer (with feature access)            |
| Open and run a query                  | Viewer (with feature access)            |
| Create a query                        | Editor                                  |
| Rename a query                        | Editor                                  |
| Delete a query                        | Editor                                  |
| Pin results to a dashboard            | Editor                                  |
| Use the Query Assistant               | Editor                                  |
| Create multi-source or Python queries | Editor (with the Python runner feature) |

Individual data sources can also be restricted — a source you don't have update access to cannot be selected when creating a query.
