VaultQuery

approvedunreviewed

by bobstanton

Execute SELECT, INSERT, UPDATE, and DELETE statements on notes, properties, tasks, tables, headings and links using SQL and SQLite.

★ 6 stars↓ 4,035 downloadsUpdated 19d agoMIT

VaultQuery

Query and update notes using SQL. Display results as a table, chart, calendar, or using JavaScript.

Documentation site: https://vaultquery.stanton.dev/

Web sandbox: https://sandbox.obsidian.stanton.dev/

Code Blocks

Code BlockDescription
vaultqueryExecute SQL queries, display results in SlickGrid or JavaScript rendering
vaultquery-nlTurn a natural-language request into a query or visualization
vaultquery-writeExecute INSERT, UPDATE, DELETE with before/after preview
vaultquery-chartRender query results as Chart.js visualizations
vaultquery-chart-helpDisplay chart output reference and examples
vaultquery-calendarRender query results as a FullCalendar calendar
vaultquery-markdownRender query results as a markdown table
vaultquery-markdown-helpDisplay markdown output reference and examples
vaultquery-calendar-helpDisplay calendar output reference and examples
vaultquery-schemaDisplay database schema documentation
vaultquery-viewDefine reusable SQL views
vaultquery-functionDefine custom SQL functions in JavaScript
vaultquery-helpDisplay built-in help documentation
vaultquery-function-helpDisplay function reference
vaultquery-examplesDisplay example collections
vaultquery-api-helpAPI guide for third-party plugin developers

Getting started

Add a vaultquery code block with a SQL query:

```vaultquery
SELECT title, path, modified FROM notes
WHERE content LIKE '%important%'
ORDER BY modified DESC
LIMIT 10
```

Results render in a sortable SlickGrid table.

Reference

Use vaultquery-help for in-app help and vaultquery-schema for available tables and columns.

Write Operations (INSERT, UPDATE, DELETE)

See write limits and failure handling.

Use vaultquery-write to preview and apply changes:

```vaultquery-write
-- Add a new note
INSERT INTO notes (path, content)
VALUES ('Condo Notes.md', '# Shopping List for new Condo');

-- Add a new task
INSERT INTO tasks (path, task_text, status)
VALUES ('Condo Notes.md', 'Buy plasma TV', 'TODO');

-- Add a new tag
INSERT INTO tags (path, tag_name)
VALUES ('Condo Notes.md', 'party-pad');

-- Add a new link
INSERT INTO links (path, link_target)
VALUES ('Condo Notes.md', 'Office/Dinner Party Plan.md');

-- Add a heading at a specific line
INSERT INTO headings (path, level, heading_text, line_number)
VALUES ('Condo Notes.md', 2, 'Sliding glass door repair quotes:', 4);

-- Add a tag at the start of a line
INSERT INTO tags (path, tag_name, line_number, insert_position)
VALUES ('Condo Notes.md', 'fake-overtime-assignment', 3, 'line_end');

-- Create a new table at a specific line using table_rows view
INSERT INTO table_rows (path, table_index, row_json, table_line_number)
VALUES ('Condo Notes.md', 1, json('{"Vendor": "", "Price": ""}'), 5);
```
```vaultquery-write
WITH
    -- Select all notes in the Projects folder
    project_notes AS (
      SELECT path, title FROM notes
      WHERE path LIKE 'Projects/%'
      ORDER BY title
    ),
    -- Create a flattened list of links to those notes
    flattenedLinks AS (
      SELECT GROUP_CONCAT('- ' || link(path, title), '\n') as list
      FROM project_notes
    )
-- Create an index linking to each note in the Projects folder
INSERT INTO notes (path, content)
SELECT
'Projects/Index.md',
'# Project Index

' || COALESCE(list, '_No projects found_')
FROM flattenedLinks;
```

UPDATE Operations

```vaultquery-write
UPDATE notes
SET content = content || '\n\nList condo on eBay at 80% of purchase price.'
WHERE path = 'Condo Notes.md'
```

DELETE Operations

```vaultquery-write
DELETE FROM notes
WHERE path = 'Condo Notes.md'
```

Markdown Table Export

Use vaultquery-markdown to render query results as a Markdown table.

```vaultquery-markdown
SELECT title, path, modified FROM notes
WHERE content LIKE '%important%'
ORDER BY modified DESC
LIMIT 10
```

Markdown Configuration Options

Configure the markdown output with a config: section:

```vaultquery-markdown
SELECT title, path, size
FROM notes
ORDER BY size DESC
LIMIT 10;

config:
alignment: left, left, right
```

Available config options:

  • alignment: Column alignments (left, center, right)

JavaScript Rendering

```vaultquery
SELECT title, path, modified FROM notes
WHERE content LIKE '%important%'
ORDER BY modified DESC
LIMIT 10;

template:
return `
  <div>
    <h3>Important Notes (${count} results)</h3>
    <ul>
      ${results.map(note => `
        <li>
          ${h.link(note.path, note.title)} -
          <em>${h.formatDate(note.modified)}</em>
        </li>
      `).join('')}
    </ul>
  </div>
`;
```

JavaScript rendering code receives these variables:

  • results - Array of query result rows
  • query - The SQL query that was executed
  • count - Number of results
  • h - Helper functions object

Inline Query Values

Use inline code in the form vq{SQL} to render the first column of the first row directly in surrounding text:

The hike was `vq{SELECT value FROM properties WHERE key = 'distance' AND path = '{this.path}' LIMIT 1}` miles.

Inline query values are read-only and only allow SELECT or WITH statements.

Obsidian CLI

vaultquery:query runs SQL from the Obsidian CLI and waits for indexing to finish before executing:

obsidian vaultquery:query sql="SELECT title, path FROM notes LIMIT 5" format=json

Available formats are json, csv, tsv, md, and scalar. Use path to provide note context for {this.*} placeholders:

obsidian vaultquery:query path="Hikes/Trip.md" sql="SELECT value FROM properties WHERE path = '{this.path}' AND key = 'distance' LIMIT 1" format=scalar

JavaScript helpers

See the helper reference.

Write operations reference

Table/ViewINSERTUPDATEDELETE
notesCreates filesModifies filesDeletes files
notes_with_propertiesCreates with frontmatterModifies allDeletes files
tasksAdds tasksModifies tasksRemoves tasks
headingsAdds headingsModifies textRemoves headings
list_itemsAdds itemsModifies itemsRemoves items
propertiesAdds to YAMLModifies YAMLRemoves from YAML
table_cellsAdds cells(2)Modifies cellsRemoves cells
table_rowsAdds rows(2)Modifies rowsRemoves rows
tagsFrontmatter or inline(1)Renames tagsRemoves tags
linksAppends or at line(1)Updates linksRemoves links

(1)With line_number and optional insert_position (new_line, line_start, line_end)

(2)With line_number (table_cells) or table_line_number (table_rows) to position new tables

Write behavior:

  • tasks, headings, list_items INSERT at specified line_number or end of file (line-based elements)
  • tags INSERT adds to frontmatter when no line_number specified, or inserts inline with insert_position
  • links INSERT appends to end of file when no line_number specified, or inserts at position with insert_position
  • table_cells and table_rows INSERT can use line_number/table_line_number to create tables at specific positions
  • notes_with_properties creates files with frontmatter in one operation
  • note_properties is for properties-only queries; use notes_with_properties or properties to write frontmatter
  • table_rows handles table row manipulation with JSON

Chart output

Use vaultquery-chart to render query results as a chart. Query must use label and value columns (or x/y for scatter). Add a series column for multiple datasets.

Configuration Options

OptionDescription
typeChart type: bar, line, pie, doughnut, or scatter (required)
titleChart title displayed above the chart
datasetLabelLegend label for the dataset
xLabelX-axis label (bar, line, scatter only)
yLabelY-axis label (bar, line, scatter only)
datasetBackgroundColorFill color for bars/points
datasetBorderColorBorder color for bars/points

SQL Columns for Customization

ColumnDescription
backgroundColorPer-point fill color
borderColorPer-point border color
chartTypePer-series chart type for mixed charts (bar, line)

See chart examples for colors, multiple series, and mixed charts.

Usage for Developers

See the API guide for queries, writes, functions, and provider tables.

// Get the VaultQuery API
const vaultQuery = this.app.plugins.getPlugin('vaultquery');
if (vaultQuery?.api) {
  // Wait for indexing to complete
  await vaultQuery.api.waitForIndexing();

  // Execute queries
  const results = await vaultQuery.api.query('SELECT * FROM notes LIMIT 10');

  // Register custom functions
  vaultQuery.api.registerCustomFunction('myFunc', 'function(x) { return x * 2; }');
}

The vaultquery-api-help code block provides complete API documentation in any note.

Settings and Configuration

Indexing Features (Configurable)

  • Content Indexing: Index note content for full-text search
  • Frontmatter Indexing: Index YAML frontmatter properties
  • Table Indexing: Parse and index markdown tables
  • Task Indexing: Index task lists with priorities and due dates
  • Heading Indexing: Index note headings and structure
  • Link Indexing: Index internal and external links
  • Unresolved Link Indexing: Index links Obsidian cannot resolve to a note
  • Embed Indexing: Index embedded links such as images, PDFs, and embedded notes
  • Block Indexing: Index Obsidian block IDs
  • Tag Indexing: Index hashtags throughout notes
  • List Item Indexing: Index bulleted and numbered list items

Performance Settings

  • Maximum file size (KB): Maximum Markdown and other-file size (default: 1000 KB)
  • Exclude Patterns: Regex patterns for files to skip

The database is stored in Obsidian's Configuration Folder in /plugins/vaultquery/database.db when using disk storage.

Troubleshooting

If a grid disappears after scrolling, use its refresh button. Use the Copy debug log to clipboard command or the Console log level setting with developer console to see more details.

External folders

See external folders for supported platforms and file types.

Network Requests

Network requests depend on enabled features:

PackageURLPurpose
VaultQueryhttps://cdn.jsdelivr.net/npm/sql.js@<version>/dist/sql-wasm.wasmDownloads the WASM for the sql.js version installed when this plugin was built.
VaultQueryThe provider URL configured in settingsTranslates a natural language request into SQL and selects a VaultQuery output. Sends the database schema description, known property names, and the natural language request, plus failed SQL and error messages when a generated statement is retried.
VaultQueryThe HTTPS URL in a vaultquery-remote-csv or vaultquery-web-json blockDownloads a read-only CSV or JSON snapshot during discovery or refresh. Requests contain the source URL and optional cache validators; vault contents are not uploaded.

SQL.js loading modes:

ModeBehaviorNetwork activity
AutoLoads the versioned cache or custom path, then downloads that build's sql.js WASM.Only if the local file is missing.
Local onlyLoads sql-wasm.wasm from the plugin folder or custom path.None. Initialization fails if the file is unavailable.
CDN onlyDownloads that build's exact sql.js version from jsDelivr.One request during database initialization.

For plugin developers

Search results and similarity scores are powered by semantic analysis of your plugin's README. If your plugin isn't appearing for searches you'd expect, try updating your README to clearly describe your plugin's purpose, features, and use cases.