← Back to skills
Data & Analytics · Made here

SQL Optimizer

sql-query-optimizer · slow sql → faster sql

Reads EXPLAIN plans, finds the expensive steps, rewrites the query and proposes indexes — and proves the result set is unchanged.

Download SKILL.mdAdd to a recipe
Watch the demo0:55
Borrow a skill and use it0:55
In Claude (connector)install_skill("sql-query-optimizer")
CLIlendskill install sql-query-optimizer

SKILL.md

---
name: sql-query-optimizer
description: Diagnose and speed up slow SQL — read the EXPLAIN / EXPLAIN ANALYZE plan, find the costly operators, rewrite the query, propose indexes or partitioning, and prove results are unchanged. Use for slow queries, query tuning, index advice or 'why is this query slow'.
license: Proprietary — Lendskill original
---

# SQL Query Optimizer

Never rename the user's tables, columns or CTEs. Change only what's needed.

## 1. Facts
Dialect and version (PostgreSQL, MySQL, SQL Server, Snowflake, BigQuery…), table sizes, existing indexes, and the plan: ask for `EXPLAIN (ANALYZE, BUFFERS)` (Postgres), `EXPLAIN ANALYZE` (MySQL 8+), the actual execution plan (SQL Server) or the query profile (warehouses).

## 2. Read the plan
Find the operators with the most time or rows: sequential scans on big tables, nested loops over large inputs, sorts/hash spills to disk, row-estimate errors (estimated vs actual off by 10×+ → stale statistics).

## 3. Usual fixes (in order of safety)
1. Make predicates sargable: no functions on indexed columns (`WHERE created_at >= '2026-01-01'` not `WHERE YEAR(created_at)=2026`), no leading `%` in LIKE.
2. Filter early; select only needed columns; replace `SELECT DISTINCT` used to hide join fan-out with a correct join.
3. Rewrite correlated subqueries as joins or window functions; `EXISTS` instead of `IN` with large subqueries where the planner struggles.
4. Indexes matching WHERE + JOIN + ORDER BY column order; covering/INCLUDE indexes for hot queries. Weigh write cost.
5. Update statistics; partition or cluster very large tables on the common filter column (warehouses).

## 4. Prove it
Run old and new on the same data: row counts and a checksum (e.g. `EXCEPT` both ways returns nothing). Compare timings over several runs.

## 5. Deliver
Full rewritten query, the index DDL, before/after timings, and why each change helps.

Supporting files (0)

  • None — SKILL.md only