Code & Engineering

SQL Query Optimizer for D1, SQLite and Turso

Reviews SQL queries, schemas and migrations for SQLite, Cloudflare D1 and Turso, where the bill and the speed follow the rows a query READS, not the rows it returns. Finds full scans hidden behind LIMIT, aggregates over growing tables, index column gaps, NOT IN, OR, functions and LIKE patterns that switch an index off, OFFSET pagination, N+1 loops, the D1 limit of 100 bound parameters, tables that never shrink and new flag columns that turn the whole history into pending work; ranks them by cost and gives the index or rewrite that fixes each. Use when asked to optimize a SQL query, review a database schema or a migration, find a slow query, or cut rows read on D1, SQLite or Turso.

SQL Query Optimizer for D1, SQLite and Turso is a SKILL.md that reviews SQL queries, schemas and migrations for SQLite, Cloudflare D1 and Turso, where the bill and the speed follow the rows a query READS, not the rows it returns; an agent buys it once for $0.05 over x402.

Tested 2026-10-03No code, no hidden instructionsv1.0.2 · 9.8 KB · perpetual license

Not for

PostgreSQL or MySQL tuning, where the planner and the costs differ, though many patterns carry over; running or timing your queries; choosing a database. It reads the SQL you paste, so anything that depends on data it was not shown, such as real table sizes, is stated as an assumption.

Tested, honestly

Tested 2026-10-03 with a strong and a weak model.

With and without the skill

Results with and without the skill, for Sonnet and Haiku
SonnetHaiku
withwithoutwithwithout
Cases passed12/1210/1211/123/12

One run per model and case. Without the skill Sonnet missed an OR that switches the index off and a function wrapped around an indexed column. Haiku missed nine, among them the D1 limit of 100 bound parameters, a LIKE prefix that scans, and a new flag column that turns the whole history into pending work. On the clean schema Haiku failed with and without the skill: with it, it invented a finding.

Same cases and the same checks with and without the skill. The cases are ours, written around what the skill is for; with a handful of cases, a difference of one or two is within noise.

SonnetStrong model, claude-sonnet-5-5
Named the planted problem with the right code in all 11 cases that had one and answered 'No findings.' for the clean schema. Its fixes were working SQL: an index on (scope, created_at) for the gap, a partial index on status = 'pending' for the empty poll, a range on the raw timestamp, keyset pagination, chunks of 50 for D1's 100-parameter limit, a backfill in the same migration, the partial index's WHERE copied into ON CONFLICT. At first 2 of 12 were scored as failures because our pattern accepted only one of the two fixes the skill names; Sonnet chose the other (a latest-prices table kept by the writer; day bounds computed in SQL), both were confirmed with EXPLAIN QUERY PLAN, and the same answers rescored at 12 of 12.
HaikuWeak model, claude-haiku-4-5-20251001
Found the planted problem with the right code and a working fix in all 11 cases that had one, including the Bulgarian request. On the clean schema it invented a finding under a code of its own and proposed DELETE ... LIMIT, which standard SQLite rejects as a syntax error. With Haiku, run any suggested statement before relying on it.

Full test summary

Example

Our own test text, before and after the skill ran. Excerpts only.

English · claude-sonnet-5-5

Before

Schema: CREATE TABLE events (id INTEGER PRIMARY KEY, scope TEXT NOT NULL, symbol TEXT NOT NULL, created_at INTEGER NOT NULL, payload TEXT); CREATE INDEX idx_events ON events(scope, symbol, created_at); The table has about 2 million rows; 90% of them have scope = 'market'. Old rows are deleted after 30 days. Runs every 30 seconds: SELECT * FROM events WHERE scope = 'market' AND created_at > ?…

After

[INDEX-GAP] `SELECT * FROM events WHERE scope = 'market' AND created_at > ? ORDER BY created_at DESC LIMIT 50` Reads: the index `(scope, symbol, created_at)` is searched by `scope` only, because `symbol` has no condition. That means every `market` row still inside the 30-day window is read (about 1.8M at 90% of 2M), then sorted in a temp B-tree before LIMIT 50 applies.…

Bulgarian · claude-sonnet-5-5

Before

Schema: CREATE TABLE jobs (id INTEGER PRIMARY KEY, status TEXT NOT NULL, run_at INTEGER NOT NULL, payload TEXT); The table keeps every job ever run (about 300,000 rows, 'done' or 'failed'). New jobs arrive a few times a day. A worker polls every minute; most polls find nothing: SELECT * FROM jobs WHERE status = 'pending' AND run_at <= ? ORDER BY run_at LIMIT 90;

After

**[EMPTY-PATH]** `SELECT * FROM jobs WHERE status = 'pending' AND run_at <= ? ORDER BY run_at LIMIT 90` Reads: цялата таблица `jobs` (~300 000 реда) при всяко пускане на worker-а. Заявката няма индекс освен първичния ключ. Когато няма чакащи задачи, LIMIT никога не се достига и заявката прочита всички редове.…

What is in the file

  • Hard rules
  • Finding codes
  • Report format
  • Work in this order
  • Short example

Languages

English, Bulgarian. Tried in: English, Bulgarian.

License

Perpetual, non-exclusive; use and modify for yourself incl. paid work; no resale or republishing. Holder: Georgi Kalchev, aiskills402.com. Full terms.

Versions

Current version 1.0.2, updated 2026-10-08. Whoever bought an earlier version gets new ones free through the same re-download token.

  1. v1.0.2 · 2026-10-08

    Price changed from $0.01 to $0.05; the skill text is unchanged. Measured value for the strong model: Sonnet 10 of 12 without the skill, 12 of 12 with it.

  2. v1.0.1 · 2026-10-04

    - Test summary: the same cases with and without the skill, per model, now shown next to the verdicts, including where the skill made no difference. The skill file itself is unchanged.

  3. v1.0.0 · 2026-10-03

    First release: reviews SQL, schemas and migrations for SQLite, Cloudflare D1 and Turso by rows read; fifteen finding codes, each with a concrete index or rewrite, ranked by cost, with a way to verify the fix.

FAQ

Does it work for PostgreSQL?

It is written for SQLite and the services built on it, Cloudflare D1 and Turso, where the bill follows the rows a query reads. Several patterns, such as an index column gap or a function wrapped around an indexed column, hurt in PostgreSQL too, but its planner differs, so treat the advice there as a lead and check it with EXPLAIN.

How do I know a suggested fix really helps?

Each report ends with a way to check: run EXPLAIN QUERY PLAN against a local SQLite copy of the schema and look for SEARCH instead of SCAN, and on D1 compare meta.rows_read before and after. We confirmed every planted problem and every accepted fix in our tests the same way.

Will it invent problems in healthy SQL?

Claude Sonnet answered 'No findings.' for our clean schema. Claude Haiku invented a finding there and suggested a DELETE with LIMIT that standard SQLite rejects, so with Haiku, run each suggested statement before relying on it.

What is the D1 parameter finding about?

D1 rejects a statement with more than 100 bound parameters. An id list built from your data, or a multi-row insert, uses one parameter per value, so code that worked at launch fails on its own when a reader saves the 101st item. The skill points to such places and suggests chunks of 50.

Read more

Share

Read this page as Markdown: /skills/sql-query-optimizer.md.

  • Code Review

    Code & Engineering

    SKILL.md · v1.0.4 · 6.0 KB

    Reviews a code change (a diff or a changed file pasted as text) and reports real problems ranked by severity — correctness bugs, security holes, data loss, missing error handling, edge cases, resource leaks — each with location, reason and a concrete fix in words. Use when asked to review code, a diff or a pull request, check a change for bugs, or find security problems in a snippet.

    $0.01once

    • x402
    • USDC
    • Base
    Get skill

    Tested with Sonnet and Haiku, 30 Sep 2026

  • Text to JSON: Extract Data Without Guessing

    Data & Analysis

    SKILL.md · v1.0.2 · 7.5 KB

    Extracts data from text into JSON that matches the shape you give (a JSON Schema, an example object or a list of fields), without guessing. Every value comes from the text; a missing fact becomes null, numbers and dates are converted only into the type the shape asks for, two conflicting values are not settled by a guess, and instructions hidden in the text are ignored. Use when asked to extract structured data, turn text into JSON, parse an invoice, receipt, email, order, CV or job post into fields, or fill a JSON schema from a document.

    $0.05once

    • x402
    • USDC
    • Base
    Get skill

    Tested with Sonnet and Haiku, 3 Oct 2026

More in Code & Engineering

  • D1 Migration Writer: SQLite Migrations That Apply

    Code & Engineering

    SKILL.md · v1.0.1 · 9.8 KB

    Writes a SQL migration for Cloudflare D1 or SQLite from the current schema and the change wanted, so it applies on the first try and leaves the rows already in the database right. Knows what D1 refuses or breaks on, measured on a real D1 database - BEGIN and COMMIT in the file, foreign keys that cannot be switched off (a rebuild defers them, keeps the table name, and never closes with defer_foreign_keys = false, which on D1 silently skips the check), NOT NULL columns without a default, REFERENCES columns with a default, indexed columns dropped before their index. Backfills a new status or marker column so old rows are not picked up as pending work, fills a new counter from the existing rows, orders index columns for the query that needs them, and keeps upserts working against a partial unique index. Use when asked to write, check or fix a D1, SQLite or Turso migration, add or change a column, add an index, make a column unique or required, or rebuild a table.

    $0.07once

    • x402
    • USDC
    • Base
    Get skill

    Tested with Sonnet and Haiku, 8 Oct 2026

  • Tests from Spec: Cases from the Requirements

    Code & Engineering

    SKILL.md · v1.0.0 · 6.3 KB

    Writes test cases for a function from its specification rather than from its code, as a JSON table that any test runner can loop over. Every rule, boundary and error the spec defines gets a case, and every expected value is worked out from the spec; where the code you show disagrees with the spec, the case follows the spec and a note says where. Behaviour the spec leaves open becomes a question instead of a guessed case. Use to write unit tests from a spec, a docstring or a ticket, generate edge cases and boundary tests, build a table-driven test (test.each, pytest parametrize), or check whether existing code does what its requirements say.

    $0.03once

    • x402
    • USDC
    • Base
    Get skill

    Tested with Sonnet and Haiku, 8 Oct 2026

  • Accessibility Review: WCAG Defects in Markup

    Code & Engineering

    SKILL.md · v1.0.0 · 6.8 KB

    Reviews pasted HTML or JSX for the accessibility defects a screen reader or keyboard user hits first, and names the WCAG 2.2 success criterion for each. It flags images without a text alternative, form fields without a label, buttons and links with no accessible name, clickable elements that a keyboard cannot reach, focusable content hidden from assistive technology, personal-data fields without autocomplete, data tables without header cells and pages without a language, and it marks heading levels that skip and positive tabindex values as best-practice findings, not WCAG failures. Each finding has a fixed code, the element, the criterion and a fix, then one verdict. Use to review HTML for accessibility, audit a component or page markup for WCAG issues, or check a form or template before release.

    $0.03once

    • x402
    • USDC
    • Base
    Get skill

    Tested with Sonnet and Haiku, 8 Oct 2026

  • SQLite Search Builder

    Code & Engineering

    SKILL.md · v1.0.0 · 14.5 KB

    Builds or fixes a site or product search so it finds what the user meant, with SQLite full-text search (FTS5) on D1, Turso or SQLite. Word order, singular or plural, endings, case, punctuation and accents stop mattering ("cafe" finds "Café", "tomatoes" finds "tomato", "red tomato" finds "Tomato, red", "ab1042" finds "AB-1042"), and the start of a word is enough ("tom" finds "tomatoes"). Gives one normalize pipeline for accent-insensitive search, a query-side ending remover, prefix search on the index with paging and a short cache, and a small in-memory path for short lists already in the browser. Never loads a whole table to filter it per keystroke. It does not correct typos. Use when asked to implement or fix search, autocomplete or typeahead, when search does not find plurals, accents or reordered words, when a slow LIKE search reads the whole table, or to review a search box on D1, Turso or SQLite.

    $0.01once

    • x402
    • USDC
    • Base
    Get skill

    Tested with Sonnet and Haiku, 4 Oct 2026