Agent skill

Optimizing SQL Queries

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Execute use when you need to work with query optimization. An agent skill from jeremylongshore/tons-of-skills-marketplace.

MITAuto-check passedDatabases

Install Optimizing SQL Queries

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill optimizing-sql-queries -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace optimizing-sql-queries --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/optimizing-sql-queries .claude/skills/optimizing-sql-queries && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
optimizing-sql-queries
GitHub stars
2.8k
Token cost
~1.7k tokens
SKILL.md length
844 words
Files
6 (incl. scripts, references, assets)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Execute use when you need to work with query optimization. An agent skill from jeremylongshore/tons-of-skills-marketplace.

  • Works in 10 steps: Examine the original query structure and… → Analyze the execution plan to identify… → Rewrite subqueries as JOINs where… → …
  • You need to work with query optimization
  • SKILL.md covers Overview, Prerequisites, Instructions and Output, plus 3 more sections
  • Runs Python scripts from its folder

What it does

Optimizing SQL Queries is an agent skill from jeremylongshore/tons-of-skills-marketplace. Execute use when you need to work with query optimization. This skill provides query performance analysis with comprehensive guidance and automation. Trigger with phrases like "optimize queries", "analyze performance", or "improve query speed".

Its SKILL.md is about 1.7k tokens, which your agent loads only when the skill is triggered. The skill folder holds 8 other files, including scripts, reference files and assets (for example `assets/README.md`, `references/README.md` and `scripts/README.md`). Compatibility notes: Designed for Claude Code

It sits in Databases, covering Query optimization and SQL. It works with SQL, PostgreSQL and MySQL. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • You need to work with query optimization
  • With phrases like optimize queries
  • Analyze performance
  • Improve query speed

Example prompts

  • “optimize queries”
  • “analyze performance”
  • “improve query speed”
  • “/optimizing-sql-queries”

Requirements

  • Python 3
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit, Grep, Glob, Bash(psql:*), Bash(mysql:*), Bash(mongosh:*)

Workflow steps

10 steps, taken from the first numbered list in SKILL.md.

  1. Examine the original query structure and identify common anti-patterns
  2. Analyze the execution plan to identify the most expensive operation nodes. Focus optimization effort on the node consuming the most time…
  3. Rewrite subqueries as JOINs where possible. Convert correlated subqueries to lateral joins (PostgreSQL) or derived tables. Replace IN…
  4. Optimize JOIN ordering for the query planner: place the most selective table (fewest matching rows after WHERE filters) as the driving…
  5. Replace multiple OR conditions on the same column with IN (...): change WHERE status = 'active' OR status = 'pending' to WHERE status IN…
  6. Apply window functions to replace self-joins or correlated subqueries. Use ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) for…
  7. Leverage CTEs (Common Table Expressions) for readability but be aware that PostgreSQL versions before 12 materialize all CTEs. For…
  8. Optimize aggregation queries by filtering before grouping (WHERE is more efficient than HAVING for non-aggregate conditions), using…
  9. Test the rewritten query with EXPLAIN ANALYZE and compare execution time, row estimates vs. actuals, and buffer usage against the…
  10. Document each change made, the reason for the change, and the measured impact so the development team understands and can apply similar…

What it can do on your machine

Read from SKILL.md and the folder at commit 23ea8d4. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit
    • Grep
    • Glob
    • Bash(psql:*)
    • Bash(mysql:*)
    • Bash(mongosh:*)

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 3 files in scripts/ (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • postgresql.org
    • use-the-index-luke.com
    • modern-sql.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Optimizing SQL Queries loads about 1.7k tokens when it runs, and up to ~1.8k if it reads all its reference files. Until then it costs about 67 tokens; SKILL.md has 844 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~67
When it runs · the whole SKILL.md, loaded when a task matches
~1.7k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~1.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit 23ea8d4, republished under its MIT licence (© jeremylongshore). 844 words, ~1,747 tokens.

Download SKILL.mdSave it as .claude/skills/optimizing-sql-queries/SKILL.md (or your agent's skills folder). This skill also uses 5 other files; get the full folder from GitHub.
name
optimizing-sql-queries
description
Execute use when you need to work with query optimization. This skill provides query performance analysis with comprehensive guidance and automation. Trigger with phrases like "optimize queries", "analyze performance", or "improve query speed".
allowed-tools
Read, Write, Edit, Grep, Glob, Bash(psql:*), Bash(mysql:*), Bash(mongosh:*)
compatibility
Designed for Claude Code
version
1.27.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
license
MIT
tags
database, performance, optimizing-sql

SQL 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 ANALYZE output (PostgreSQL) or EXPLAIN FORMAT=JSON output (MySQL) for the query
  • Table row counts and approximate data distribution for involved tables
  • psql or mysql CLI for testing rewrites
  • Knowledge of the application's acceptable result ordering and NULL handling requirements

Instructions

  1. 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 as JOIN or EXISTS
    • DISTINCT used to mask duplicate rows from incorrect JOINs
    • Functions applied to indexed columns in WHERE clauses (WHERE UPPER(name) = 'FOO')
    • OR conditions that prevent index usage
    • NOT IN with nullable columns (produces wrong results and poor plans)
  2. 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.

  3. Rewrite subqueries as JOINs where possible. Convert correlated subqueries to lateral joins (PostgreSQL) or derived tables. Replace IN (SELECT ...) with EXISTS (SELECT 1 ...) for existence checks since EXISTS short-circuits after the first match.

  4. Optimize JOIN ordering for the query planner: place the most selective table (fewest matching rows after WHERE filters) as the driving table. Use JOIN hints only as a last resort since the optimizer usually picks the correct order with accurate statistics.

  5. Replace multiple OR conditions on the same column with IN (...): change WHERE status = 'active' OR status = 'pending' to WHERE status IN ('active', 'pending'). For OR across different columns, consider UNION ALL of two simpler queries.

  6. 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 of GROUP BY with subqueries.

  7. 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.

  8. Optimize aggregation queries by filtering before grouping (WHERE is more efficient than HAVING for non-aggregate conditions), using partial indexes for filtered aggregates, and considering materialized views for expensive recurring aggregations.

  9. Test the rewritten query with EXPLAIN ANALYZE and 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.

  10. 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)
Show full SKILL.md (331 more words)Show less

Error Handling

ErrorCauseSolution
Rewritten query returns different resultsJOIN type change (INNER vs LEFT) or NULL handling differenceVerify result sets match with EXCEPT query; preserve original JOIN types; handle NULLs explicitly with COALESCE
Optimized query slower than originalStatistics outdated causing planner to choose wrong planRun ANALYZE on involved tables; compare estimated rows vs actual rows in EXPLAIN; consider SET enable_seqscan = off to test alternative plans
CTE materialization hurting performancePostgreSQL <12 materializes CTEs preventing predicate pushdownInline the CTE as a subquery; upgrade PostgreSQL; add AS NOT MATERIALIZED hint in PostgreSQL 12+
Window function query uses excessive memoryLarge partition sizes with ORDER BY in window specificationAdd LIMIT to outer query; use index matching the PARTITION BY and ORDER BY columns; increase work_mem for the session
UNION ALL produces duplicatesOverlapping conditions in constituent queriesAdd 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

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 5 other files (scripts, references, assets) in skills/.curated/optimizing-sql-queries of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • assets/README.md
  • references/README.md
  • scripts/README.md
  • scripts/analyze_query.py
  • scripts/explain_query.py

Open the folder on GitHubat commit 23ea8d4

Compare with similar skills

Optimizing SQL Queries next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Optimizing SQL Queries compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Optimizing SQL Queries this skilljeremylongshore/tons-of-skills-marketplace2.8k—~1.7kAutomated safety check: PassMIT
SQL ProJeffallan/claude-skills12k—~1.3kAutomated safety check: PassMIT
SQL Optimizationgithub/awesome-copilot40k2 repos~2.3kAutomated safety check: PassMIT
Query Expertjamesrochabrun/skills216—~4.3kAutomated safety check: PassMIT
Optimizing SQLancoleman/ai-design-components526—~3kAutomated safety check: PassMIT
Dsqlawslabs/agent-plugins915—~6.9kAutomated safety check: PassApache-2.0

Similar skills

  • SQL Pro

    Jeffallan/claude-skills

    Optimizes SQL queries and designs schemas using CTEs, window functions, covering indexes and EXPLAIN ANALYZE, with notes on dialect differences between major databases.

    12k GitHub stars~1.3k tokensUpdated 4 days ago
    DatabasesAuto-check passed
  • SQL Optimization

    github/awesome-copilot

    Official

    Universal SQL performance optimization assistant for comprehensive query tuning, indexing strategies, and database performance analysis across all SQL databases (MySQL, PostgreSQL, SQL Server…

    40k GitHub starsUsed in 2 repos~2.3k tokens
    DatabasesAuto-check passed
  • Query Expert

    jamesrochabrun/skills

    Master SQL and database queries across multiple systems. An agent skill from jamesrochabrun/skills.

    216 GitHub stars~4.3k tokensUpdated 8 mo ago
    DatabasesAuto-check passed
  • Optimizing SQL

    ancoleman/ai-design-components

    Optimize SQL query performance through EXPLAIN analysis, indexing strategies, and query rewriting for PostgreSQL, MySQL, and SQL Server.

    526 GitHub stars~3k tokensUpdated 10 mo ago
    DatabasesAuto-check passed
  • Dsql

    awslabs/agent-plugins

    Official

    Build with Aurora DSQL — manage schemas, execute queries, handle migrations, diagnose query plans, diagnose cluster performance, load data, and develop applications with a serverless, distributed…

    915 GitHub stars~6.9k tokensUpdated 2 days ago
    DatabasesAuto-check passed
  • Agent SQL Pro

    xiaoyuge886/aigc

    Expert SQL developer specializing in complex query optimization, database design, and performance tuning across PostgreSQL, MySQL, SQL Server, and Oracle.

    198 GitHub stars~315 tokensUpdated 2 mo ago
    DatabasesAuto-check passed

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Analyzing Text With NLP

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to perform natural language processing and text analysis using the nlp-text-analyzer plugin.

    2.8k GitHub starsUsed in 1 repo~819 tokens
    Auto-check passed
  • Building Neural Networks

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill allows AI assistant to construct and configure neural network architectures using the neural-network-builder plugin.

    2.8k GitHub starsUsed in 1 repo~1k tokens
    Auto-check passed
  • Detecting Data Anomalies

    jeremylongshore/tons-of-skills-marketplace

    Process identify anomalies and outliers in datasets using machine learning algorithms.

    2.8k GitHub starsUsed in 1 repo~1.4k tokens
    Auto-check passed
  • Explaining Machine Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill enables AI assistant to provide interpretability and explainability for machine learning models.

    2.8k GitHub starsUsed in 1 repo~1k tokens
    Auto-check passed
  • Optimizing Prompts

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill optimizes prompts for large language models (llms) to reduce token usage, lower costs, and improve performance.

    2.8k GitHub starsUsed in 1 repo~1k tokens
    Auto-check passed

Categories

Questions about Optimizing SQL Queries

What does Optimizing SQL Queries do?

Execute use when you need to work with query optimization. An agent skill from jeremylongshore/tons-of-skills-marketplace. Optimizing SQL Queries is an agent skill from jeremylongshore/tons-of-skills-marketplace. Execute use when you need to work with query optimization.

When should I use Optimizing SQL Queries?

Optimizing SQL Queries fits situations like: you need to work with query optimization; with phrases like optimize queries; analyze performance; improve query speed.

How do I install Optimizing SQL Queries in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill optimizing-sql-queries -a claude-code`. Or copy the skill folder (skills/.curated/optimizing-sql-queries in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/optimizing-sql-queries in your project. Claude Code loads it when a task matches its description.

How do I install Optimizing SQL Queries in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill optimizing-sql-queries -a codex`. Or copy the skill folder (skills/.curated/optimizing-sql-queries in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/optimizing-sql-queries in your project. Codex loads it when a task matches its description.

Can I use Optimizing SQL Queries in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill optimizing-sql-queries -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/optimizing-sql-queries, .gemini/skills/optimizing-sql-queries, .github/skills/optimizing-sql-queries and .opencode/skills/optimizing-sql-queries in your project.

What does Optimizing SQL Queries need to run?

Going by SKILL.md and its folder, Optimizing SQL Queries needs Python for the scripts in its folder. Our summary lists: Python 3. Its frontmatter pre-approves these tools: Read, Write, Edit, Grep, Glob, Bash(psql:*), Bash(mysql:*), Bash(mongosh:*). Compatibility (from SKILL.md): Designed for Claude Code.

Does Optimizing SQL Queries access the network?

SKILL.md names 3 domains. As links in the text: postgresql.org, use-the-index-luke.com and modern-sql.com. This is read from the text; nothing was executed.

Is Optimizing SQL Queries safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Optimizing SQL Queries use?

Optimizing SQL Queries is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Optimizing SQL Queries use?

About 1.7k tokens (SKILL.md is roughly 7k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 16 tokens, read only when the agent opens those files.

What are the alternatives to Optimizing SQL Queries?

Skills that share tags, products or a category with Optimizing SQL Queries: SQL Pro (Jeffallan/claude-skills, 12k stars), SQL Optimization (github/awesome-copilot, 40k stars), Query Expert (jamesrochabrun/skills, 216 stars) and Optimizing SQL (ancoleman/ai-design-components, 526 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Optimizing SQL Queries?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,821 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 8, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.