Skip to content

commandDatabases

Explain Query

Explains what a SQL query returns, how the database plans to run it and which parts will be slow, using the real plan if allowed.

npx workspacetemplates add explain-query --tool claude-code

Writes 1 file to .claude/commands/

.claude/commands/explain-query.md14 lines · 1.2 KBFile
---
description: Explains what a SQL query returns, how the database plans to run it and which parts will be slow, using the real plan if allowed.
argument-hint: "[SQL text or file:line]"
---

Explain this query: $ARGUMENTS (SQL text, or a file and line where it lives).

1. Identify the dialect and find the schema and indexes for each table involved. If the query is in application code, extract the SQL and note the bound parameters.
2. Say in two sentences what the query returns and for whom. Then walk through it in logical order: FROM and joins, WHERE, GROUP BY, HAVING, window functions, ORDER BY, LIMIT. One line each.
3. Predict the physical plan: which index each filter could use, join method and order, and where a sort or temp table is needed.
4. Offer to run `EXPLAIN` (never `EXPLAIN ANALYZE` on writes, since it executes them). Run it only when a read-only connection is available and the user agrees.
5. Flag slow spots: functions on indexed columns, leading wildcard LIKE, SELECT *, OR across columns, correlated subqueries, missing join indexes, OFFSET paging.

Report the explanation, a ranked list of the slow spots with evidence, and one rewrite per spot. Do not alter any code or schema.

What it does

Reading a long query with several joins and subqueries is slow even for experts. This command breaks it into steps in plain words, then shows how the database will most likely run it.

If you allow it, it fetches the actual execution plan with EXPLAIN and points to the specific node that costs the most, such as a sequential scan over a large table.

Example

you › /explain-query src/reports/monthly.sql

agent › Returns revenue per product for each month of the year for active accounts.
Plan: seq scan on events (4.1M rows, no index on created_at), hash join to accounts, sort for GROUP BY.
Slow spot 1: DATE(created_at) blocks the index; use a range. Rewrite shown.

Questions

Will it run my query?
Only EXPLAIN on a read-only connection and only after you agree. Plain explanation needs no database access.
Does it change the query?
It proposes rewrites in the report and leaves your files alone.
  • Add Index

    CommandDatabases

    Free
  • Schema Diff Review

    CommandDatabases

    Free
  • Seed Database

    CommandDatabases

    Free
  • Write Migration

    CommandDatabases

    Free