SQL queries & charts

Need a total by month, a join across two tables or a single headline number? Write a SQL query in a page. OpenThink runs it over the space's data tables and shows a live result that updates as the data changes.

Write a query block

Put the query in a code block labelled `sql`. The example below runs live on the sample table [Expenses](https://openthink.app/n/898391379d30) in the Examples folder:

```sql as=chart chart=bar

SELECT strftime('%m/%Y', "Date") AS "Month", SUM("Amount") AS "Spent"

FROM "Expenses"

GROUP BY 1

ORDER BY MIN("Date")

```

The source of this block is three backticks followed by `sql as=chart chart=bar` on the opening line, then the query:

```

SELECT strftime('%m/%Y', "Date") AS "Month", SUM("Amount") AS "Spent"

FROM "Expenses"

GROUP BY 1

ORDER BY MIN("Date")

```

and three backticks on the closing line.

Options

Add options after `sql` on the opening line:

| Option | Values |

|---|---|

| `as` | `table` (default), `chart`, or `number` (first row, one big number per column) |

| `chart` | `bar` or `line` |

| `x` | Result column for the horizontal axis (default: the first column) |

| `y` | Number columns to plot, comma-separated (default: all other number columns) |

Wrap values that contain spaces in double quotes, like `x="Month name"`.

The SQL

- The dialect is **SQLite**, and queries are **read-only**: only `SELECT` and `WITH`.

- Refer to tables and columns by their **names in double quotes**, exactly as they appear in the tree: `FROM "Expenses"`, `"Amount"`.

- Tables are looked up in the page's own space. If two tables in the space share a name, the block shows an error.

How column types appear in SQL

| Column type | In SQL |

|---|---|

| Number | A number (money is a plain number) |

| Date | Text `'yyyy-mm-dd'` — works with comparisons and `strftime` |

| Checkbox | `0` or `1` |

| Select | The option name |

| Multi-select | Option names joined by `", "` |

Every table also has a hidden `"_id"` column with the row's id.

Formatting of results

- A money column — or `SUM` / `AVG` / `MIN` / `MAX` of it — shows in the column's currency.

- `COUNT` shows as a plain number.

- A result column whose name contains `%` shows as a percentage (values 0–100).

Who can see the results

The query runs in the viewer's browser, so anyone who can open the page can read all rows of the tables the block mentions. Keep private data in a separate space or a [sealed table](https://openthink.app/n/26c72c31ab9c).