
SQL Query Optimizer
FreeEnhance SQL query performance with automated analysis.
Free · Opens the source repo
What SQL Query Optimizer does
The SQL Query Optimizer skill is designed for database developers and engineers looking to improve the performance of their SQL queries. By analyzing slow queries and their execution plans, this skill provides actionable insights and rewrites that can significantly enhance query speed. It focuses on identifying common anti-patterns, restructuring queries, and applying optimizations tailored for PostgreSQL and MySQL databases.
To use this skill effectively, users need to provide the original SQL query, its execution time, and the output from EXPLAIN ANALYZE for PostgreSQL or EXPLAIN FORMAT=JSON for MySQL. The skill then examines the query structure, identifies inefficiencies such as unnecessary SELECT * statements or poorly structured JOINs, and recommends optimizations. It generates an optimized query along with performance metrics that compare the original and improved versions, ensuring users can see the tangible benefits of the changes made.
In addition to rewriting queries, the skill also suggests necessary index changes to support the optimized queries, helping to ensure that the improvements are sustainable. With a focus on common SQL pitfalls, this skill is particularly useful for teams that regularly deal with complex queries or large datasets, allowing them to maintain efficient database interactions.
Documentation is also a key feature of this skill, as it provides a detailed report of the changes made, the rationale behind them, and the expected performance improvements. This not only aids in immediate query optimization but also serves as a reference for future query development, helping teams to adopt best practices over time.
When to use it
Use this skill when you have slow SQL queries that need optimization or when you're looking to improve database performance systematically.
When not to use it
This skill may not be suitable for very simple queries or when performance issues stem from application-level logic rather than database queries.
What you can build with it
Improving a Slow Reporting Query
A developer uses this skill to optimize a reporting query that takes several seconds to execute, resulting in a significant reduction in runtime.
Refactoring Complex JOINs
A database engineer applies the skill to refactor complex JOIN statements in their SQL queries, leading to clearer and more efficient code.
Enhancing Application Performance
A team leverages this skill to analyze and optimize multiple SQL queries in their application, resulting in improved overall application performance.
How to install SQL Query Optimizer
View source1. Install with the skills CLI
npx skills add jeremylongshore/claude-code-plugins-plus-skills/optimizing-sql-queries --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by jeremylongshoreSQL Query Optimizer
Overview
Rewrite SQL queries for maximum performance by eliminating anti-patterns, restructuring JOINs, leveraging window functions, and applying database-specific optimizations for PostgreSQL and MySQL. This skill takes a slow query and its execution plan as input and produces an optimized version with measurable improvement, along with any supporting index changes needed.
Prerequisites
- The slow SQL query text and its current execution time
EXPLAIN ANALYZEoutput (PostgreSQL) orEXPLAIN FORMAT=JSONoutput (MySQL) for the query- Table row counts and approximate data distribution for involved tables
psqlormysqlCLI for testing rewrites- Knowledge of the application's acceptable result ordering and NULL handling requirements
Instructions
-
Examine the original query structure and identify common anti-patterns:
SELECT *instead of specific columns (forces unnecessary I/O)WHERE column IN (SELECT ...)that can be rewritten asJOINorEXISTSDISTINCTused to mask duplicate rows from incorrect JOINs- Functions applied to indexed columns in WHERE clauses (
WHERE UPPER(name) = 'FOO') ORconditions that prevent index usageNOT INwith nullable columns (produces wrong results and poor plans)
-
Analyze the execution plan to identify the most expensive operation nodes. Focus optimization effort on the node consuming the most time or processing the most rows.
-
Rewrite subqueries as JOINs where possible. Convert correlated subqueries to lateral joins (PostgreSQL) or derived tables. Replace
IN (SELECT ...)withEXISTS (SELECT 1 ...)for existence checks since EXISTS short-circuits after the first match. -
Optimize JOIN ordering for the query planner: place the most selective table (fewest matching rows after WHERE filters) as the driving table. Use
JOINhints only as a last resort since the optimizer usually picks the correct order with accurate statistics. -
Replace multiple OR conditions on the same column with
IN (...): changeWHERE status = 'active' OR status = 'pending'toWHERE status IN ('active', 'pending'). For OR across different columns, consider UNION ALL of two simpler queries. -
Apply window functions to replace self-joins or correlated subqueries. Use
ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)for top-N-per-group queries instead ofGROUP BYwith subqueries. -
Leverage CTEs (Common Table Expressions) for readability but be aware that PostgreSQL versions before 12 materialize all CTEs. For performance-critical queries on older PostgreSQL, inline the CTE as a subquery.
-
Optimize aggregation queries by filtering before grouping (
WHEREis more efficient thanHAVINGfor non-aggregate conditions), using partial indexes for filtered aggregates, and considering materialized views for expensive recurring aggregations. -
Test the rewritten query with
EXPLAIN ANALYZEand compare execution time, row estimates vs. actuals, and buffer usage against the original. The optimized version should show fewer rows processed, index scans replacing sequential scans, and lower total execution time. -
Document each change made, the reason for the change, and the measured impact so the development team understands and can apply similar patterns to future queries.
Output
- Optimized SQL query with comments explaining each structural change
- Before/after execution plans showing performance improvement
- Index recommendations (CREATE INDEX statements) needed to support the optimized query
- Anti-pattern report listing issues found in the original query with explanations
- Performance metrics comparison (execution time, rows scanned, buffer hits)
Error Handling
| Error | Cause | Solution |
|---|---|---|
| Rewritten query returns different results | JOIN type change (INNER vs LEFT) or NULL handling difference | Verify result sets match with EXCEPT query; preserve original JOIN types; handle NULLs explicitly with COALESCE |
| Optimized query slower than original | Statistics outdated causing planner to choose wrong plan | Run ANALYZE on involved tables; compare estimated rows vs actual rows in EXPLAIN; consider SET enable_seqscan = off to test alternative plans |
| CTE materialization hurting performance | PostgreSQL <12 materializes CTEs preventing predicate pushdown | Inline the CTE as a subquery; upgrade PostgreSQL; add AS NOT MATERIALIZED hint in PostgreSQL 12+ |
| Window function query uses excessive memory | Large partition sizes with ORDER BY in window specification | Add LIMIT to outer query; use index matching the PARTITION BY and ORDER BY columns; increase work_mem for the session |
| UNION ALL produces duplicates | Overlapping conditions in constituent queries | Add mutually exclusive WHERE conditions to each branch; or use UNION (with dedup cost) if overlap is unavoidable |
Examples
Converting correlated subquery to JOIN: Original: SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE region = 'US') taking 8 seconds with sequential scan on orders. Rewrite: SELECT o.* FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.region = 'US' using index on orders.customer_id reduces to 120ms.
Top-N per group with window function: Original uses self-join to find the 3 most recent orders per customer (15 seconds). Rewrite: SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn FROM orders) sub WHERE rn <= 3 with index on (customer_id, created_at DESC) completes in 400ms.
Eliminating DISTINCT from incorrect JOIN: SELECT DISTINCT o.* FROM orders o JOIN line_items li ON o.id = li.order_id WHERE li.amount > 100 scans all line items. Rewrite: SELECT o.* FROM orders o WHERE EXISTS (SELECT 1 FROM line_items li WHERE li.order_id = o.id AND li.amount > 100) eliminates the deduplication step and halves execution time.
Resources
- PostgreSQL query planning: https://www.postgresql.org/docs/current/planner-optimizer.html
- MySQL query optimization: https://dev.mysql.com/doc/refman/8.0/en/optimization.html
- SQL anti-patterns reference: https://use-the-index-luke.com/sql/where-clause
- Window functions tutorial: https://www.postgresql.org/docs/current/tutorial-window.html
- Modern SQL features: https://modern-sql.com/
Frequently asked questions about SQL Query Optimizer
Similar skills
ClickHouse Logs Queries
Efficiently manage Supabase logs with ClickHouse SQL.
EF Core D2 Database Diagram Generator
Visualize your EF Core models as D2 diagrams effortlessly.
Safe SQL Execution
Ensure secure SQL execution in Supabase applications.
Oracle to PostgreSQL Migration
Identify migration risks between Oracle and PostgreSQL.
SSMA Console
Streamline Oracle to SQL Server migrations with ease.
SQL Performance Optimization
Enhance SQL query efficiency across all databases.
