SQLLens.AI Docs
Pillar

Query Optimizer (QO)

Turn execution plans into actionable fixes: Visual Explain, ranked index DDL, Index Strategy Studio with AI Advisor and 3 AI compare (LLMs), query rewrite suggestions (MySQL), and plan issues for PostgreSQL and SQLite — all in one workbench tied to your active connection.

Overview

The Query Optimizer is a dedicated panel that opens beside your SQL editor. It analyzes the statement under your caret, scores it (0–100), and surfaces:

SQLLens.AI opens the correct workbench for your connection: Query Optimizer (MySQL/MariaDB), PostgreSQL Query Optimizer, or SQLite Query Optimizer.

Sign-in

Opening the optimizer requires a sqllens.ai Cloud session (entitlement qo on paid tiers). Local connections still work once signed in.

How to open the workbench

SQL editor CodeLens row: Run SQL, Switch Database, connection badge, Optimize, Beautify, Save as Favorite.
Place the caret inside a statement and use ⚡ Optimize on the CodeLens row (or the editor right‑click menu).

Before optimizing, confirm the sidebar Active database matches the SQL tab (same rules as Run SQL).

Workbench layout

All engines share the same shell:

AreaPurpose
HeaderConnection name, database/schema selectors (MySQL database dropdown; PostgreSQL catalog + schema), host badge, score/grade, 🔄 Re-analyze.
Query editorEditable Monaco SQL pane — change the query and re-run analysis without closing the panel.
Optimizer query (MySQL only)Read-only pane showing the SQL MySQL’s optimizer actually planned (from EXPLAIN FORMAT=JSON or warnings when available).
Toolbar stripPrimary actions: Analyze, Explain, Visual explain, Rewrites, Format, Clear, Trace, Copy Index DDL, Create Index.
Detail panelRecommendations, EXPLAIN output, trace log, or create-index modals — controlled by the toolbar.
Progress barBottom strip during analysis (plan fetch → recommendations → rewrites).

Toolbar actions (what each button does)

ButtonWhat you seeMySQLPostgreSQLSQLite
AnalyzeDefault view: recommended indexes + rewrite/tips or plan issues✓✓✓
ExplainRaw plan — table (MySQL/SQLite) or tree/visual/JSON (PostgreSQL)TableTree defaultTable
Visual explainGraphical plan tree with cost highlights✓— (use Explain → Visual tab)— (use Explain → Tree)
Rewrites / TipsFocus on query rewrite cards + optimization tips✓——
FormatBeautify SQL in the editor pane✓✓✓
ClearClear editor (and optimizer query pane on MySQL)✓✓✓
TraceHuman-readable index/optimizer algorithm log✓✓—
Copy Index DDLCopy all actionable CREATE INDEX statements✓✓✓
Create IndexOpen modal to run DDL (optionally validate with timed before/after)✓✓✓

Analyze panel (default)

Recommended indexes

Shown at the top of Analyze for every engine. Each row includes:

Rows that match an existing index (exact or prefix) are hidden from actionable lists — the trace explains “already covered.”

Index Strategy Studio (MySQL / MariaDB / PostgreSQL)

On MySQL, MariaDB, and PostgreSQL, the Analyze panel’s recommended-indexes area is the Index Strategy Studio — a tabbed canvas that separates rule-based suggestions from AI advice. SQLite shows the internal list only (no AI tabs).

Index Strategy Studio with Index Engine, AI Advisor, and 3 AI compare tabs and ranked index cards.
Index Strategy Studio — switch between Index Engine, AI Advisor, and (MySQL/MariaDB) 3 AI compare (LLMs).
TabWhat it showsWhen to use
⚙ Index EngineInternal algorithm recommendations from EXPLAIN, schema catalog, and join-aware rules — same logic as Trace.Default after Analyze; fastest, no LLM usage.
✨ AI AdvisorOne Auto-routed LLM pass for index DDL. Click ▶ Run Auto to fetch suggestions; each row shows table, columns, confidence, match vs Index Engine, and DDL.Quick second opinion with a single model choice handled by integrated routing.
🗳 3 AI compare (LLMs)Up to three slots — pick Index Engine, Auto, or a named model per slot, then ▶ Run consensus. Results rank by agreement; top picks get highlighted DDL and Create Index.MySQL/MariaDB only; requires Pro Plus plan or higher on sqllens.ai Cloud.
Existing indexes

Recommendations that exactly match an index already on the server are moved to Using Existing Indexes (already covered) on the Index Engine tab — they are not offered as new DDL. AI and consensus runs use the same catalog context; always re-run Analyze after creating indexes.

AI Advisor tab

Open the ✨ AI Advisor tab inside Index Strategy Studio after running Analyze (so Index Engine context and schema metadata are loaded).

  1. Click ▶ Run Auto — one LLM request returns index-only DDL suggestions.
  2. Review each card: target table, column list, confidence %, whether it matches Index Engine, and the proposed CREATE INDEX statement.
  3. Use per-row actions or the shared Create Index flow from the toolbar when you are ready to apply DDL.

Notes on AI Advisor cards are kept short (about one line) so you can scan quickly. For a deeper rationale, open Trace on the Index Engine tab or compare multiple models on the compare tab.

Requires sqllens.ai sign-in and an AI provider configured under Settings → AI. See LLMs & AI.

3 AI compare (LLMs)

Available on MySQL and MariaDB workbenches (not PostgreSQL or SQLite). Included on Pro Plus and higher cloud plans; Free and Pro tiers still have Index Engine and AI Advisor (Auto).

Three LLM model slots, Run consensus button, status bar, and ranked unanimous recommendation card.
3 AI compare (LLMs) — three slots, parallel run, status bar, then ranked cards with agreement chips.

Setup and run

  1. Run Analyze first so Index Engine recommendations are available as a baseline.
  2. Open the 🗳 3 AI compare (LLMs) tab.
  3. For each of up to three slots, choose — Select model —, Index Engine, Auto, or a named model from the dropdown. You can fill one, two, or all three slots.
  4. Click ▶ Run consensus. All selected sources run in parallel; a status bar shows progress until every source responds.
  5. Results appear once — changing a slot clears the previous run until you click Run consensus again.

Reading results

Recommendations are grouped into vertical ranked cards (not a wide matrix):

Identical index DDL from different sources is deduplicated into one ranked group. LLM consensus groups rank above engine-only suggestions when scores tie.

Tips

MySQL/MariaDB — rewrites & tips on Analyze

Below indexes, Analyze also shows ✏️ Rewrite Recommendations / Tips when the analyzer finds:

Each rewrite card offers Preview, Apply (replaces text in the workbench editor), and confidence/impact badges.

PostgreSQL — Issues & Impact

Instead of SQL rewrite cards, Analyze shows a table of plan issues with severity, suggestion, and impact. A summary strip includes plan cost, estimated rows, sequential vs index scans, and whether the plan used EXPLAIN ANALYZE (actual rows) or estimates only.

SQLite — Performance at a glance

Analyze adds a grade headline, chips (full scans, index lookups, automatic indexes, temp sorts), access-path before/after cards, and quick wins (create suggested indexes, run ANALYZE;).

Explain panel & sub-views

Click Explain to focus on the execution plan. MySQL and SQLite use a compact table; PostgreSQL opens a tabbed EXPLAIN section.

MySQL / MariaDB

PostgreSQL

SQLite

Visual Explain (MySQL entry)

From the editor, Visual Explain can open directly; inside the workbench, use Visual explain on the toolbar (MySQL only — PostgreSQL visual lives under Explain tabs).

Animated demo: Query Optimizer — Visual Explain, index recommendations, and measured evidence.
Visual Explain — plan tree, cost highlights, and step detail.

Trace (algorithm log)

Available on MySQL and PostgreSQL. Click Trace to see how the product parsed your SQL, scored EXPLAIN rows, and chose index recommendations. Sections typically include:

  1. User query vs optimizer query (MySQL).
  2. EXPLAIN rows / plan issues.
  3. Recommender trace (clause detection, join groups, eligible columns).
  4. Final index list and workbench pipeline notes.

Use 📋 Copy Trace when sharing with support or filing an issue.

Index recommendations & Create Index

Animated demo: Query Optimizer workbench with index suggestions and create-index flow.
Recommended indexes, copy DDL, and create-index validation.

Actions

Index types the recommender may suggest

TypeWhenNotes
BTREE (default)Equality/range filters, JOIN keys, ORDER BYComposite indexes follow column order in WHERE/JOIN/ORDER BY.
FULLTEXT (MySQL)Leading-wildcard LIKE '%term%' on text columnsMarked optional — requires rewrite to MATCH(col) AGAINST('term'); LIKE alone will not use the index.
HASH / generated hash (MySQL InnoDB)Wide TEXT/BLOB equality filtersOften paired with a query rewrite using a stored/generated CRC32/MD5 column.
SPATIAL / VECTORGeo or vector distance patternsVector indexes apply when distance is in WHERE/ORDER BY LIMIT, not only projected in SELECT.
PostgreSQLB-tree, GiST/GIN/etc. per column types and predicatesMethod policy follows catalog capabilities (see trace for method choice).
SQLiteB-tree indexes on filter/join columnsFlags automatic indexes SQLite created at runtime — prefer explicit indexes you control.

Query rewrite recommendations

Automated SQL rewrite cards are a MySQL/MariaDB workbench feature. PostgreSQL and SQLite focus on plan issues and index DDL instead of one-click SQL replacements.

MySQL — automatic rewrite types

The rewriter scans your statement and may suggest the following (sorted by impact and confidence):

RewriteTypical patternSuggested directionImpact
Function isolationUPPER(col) = 'X', LOWER(col), DATE(col), YEAR/MONTH/DAY/HOUR(col)Move function to the literal side or use a date/time range on the columnHigh
LEFT / SUBSTRINGLEFT(col,n) = 'prefix', SUBSTRING(col,1,n) = 'prefix'col LIKE 'prefix%' (escaped)High
CONCAT on columnCONCAT(col, …) = 'value'Generated stored column + index (guidance DDL)High
OR → UNIONWHERE a = 1 OR b = 2 on different columnsUNION of two SELECTsMedium
IN subquery → JOINWHERE col IN (SELECT … FROM t)INNER JOIN t ON …Medium
IN → EXISTScol IN (SELECT … WHERE …)EXISTS (SELECT 1 …)Medium
NOT IN → NOT EXISTScol NOT IN (SELECT …)NOT EXISTS (…) (NULL-safe)Medium
Correlated EXISTS → JOINSimple single-table EXISTSINNER JOIN semijoin formMedium (lower confidence)
LIMIT/OFFSET → keysetLIMIT n OFFSET > 100WHERE id > :last_id ORDER BY id LIMIT nHigh
DISTINCT → GROUP BYSELECT DISTINCT cols (not DISTINCT ON)Same columns with GROUP BYLow
HAVING → WHERENon-aggregate predicates in HAVINGPush filters to WHEREMedium
CASE → IFSimple two-branch CASE WHEN col = v …IF(col = v, …, …)Low
UNION → UNION ALLUNION without dedup needUNION ALLMedium

MySQL — index-linked query rewrites

When the index recommender proposes certain indexes, it may attach a paired rewrite:

These appear in the same rewrite list as structural rewrites and can be applied from the workbench editor.

MySQL — general optimization tips (not always auto-rewritten)

The recommendation engine adds tips when it detects patterns such as:

Tips include severity, suggested fix text, and sometimes a sample sqlFix snippet — review before running on production.

PostgreSQL — what we handle instead of rewrite cards

SQLite — what we handle instead of rewrite cards

Engine comparison (at a glance)

FeatureMySQL / MariaDBPostgreSQLSQLite
Panel titleQuery OptimizerPostgreSQL Query OptimizerSQLite Query Optimizer
Dual optimizer-query paneYesNoNo
Visual plan graphYes (toolbar)Explain → Visual tabExplain → Tree
Automatic SQL rewritesYesNoNo
Algorithm traceYesYesNo
Create index in UIYesYesYes
Profiler validate on createYesYes (EXPLAIN ANALYZE path)Wall-clock only
Batch optimize (from QLA)YesVaries by entryVaries by entry

When to optimize

Batch optimize (from slow query log)

Select multiple entries in the Query Log Optimizer and run batch analysis to collect overlapping index suggestions across statements — useful when several queries share the same missing index.

Optimizer settings

Common keys (VS Code Settings → search queryOptimizer):

Full list: Settings → Optimizer.

Tips & limits