Agent skill

Optimizing SQL

by ancoleman in ancoleman/ai-design-components

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

MITAuto-check passedDatabases

Install Optimizing SQL

skills CLI
$ npx skills add ancoleman/ai-design-components --skill optimizing-sql -a claude-code

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

GitHub CLI
$ gh skill install ancoleman/ai-design-components optimizing-sql --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/ancoleman/ai-design-components.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/optimizing-sql .claude/skills/optimizing-sql && 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
GitHub stars
526
Token cost
~3k tokens
SKILL.md length
905 words
Files
14 (incl. references)
Skills in repo
75
Repo updated
First seen
Licence
MIT

At a glance

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

  • Works in 5 steps: Analyze Query Performance → Identify Optimization Opportunities → Apply Indexing Strategies → …
  • Debugging slow queries
  • SKILL.md covers When to Use This Skill, Core Optimization Workflow, Quick Reference Tables and Database-Specific Optimizations, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Optimizing SQL is an agent skill from ancoleman/ai-design-components. Optimize SQL query performance through EXPLAIN analysis, indexing strategies, and query rewriting for PostgreSQL, MySQL, and SQL Server. Use when debugging slow queries, analyzing execution plans, or improving database performance.

Its SKILL.md is about 3k tokens, which your agent loads only when the skill is triggered. The skill folder holds 15 other files, including reference files (for example `outputs.yaml`, `references/anti-patterns.md` and `references/composite-indexes.md`).

It sits in Databases, covering SQL and Query optimization. It works with SQL, Microsoft SQL Server, MySQL and PostgreSQL. The repository describes itself as: Comprehensive UI/UX and Backend component design skills for AI-assisted development with Claude. The licence is MIT.

When your agent uses it

  • Debugging slow queries
  • Analyzing execution plans
  • Improving database performance

Example prompts

  • “/optimizing-sql”

Workflow steps

5 steps, taken from the step headings in SKILL.md.

  1. Analyze Query Performance
  2. Identify Optimization Opportunities
  3. Apply Indexing Strategies
  4. Design Composite Indexes
  5. Rewrite Inefficient Queries

What it can do on your machine

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

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are sql).

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

  • Network

    No URLs in SKILL.md.

    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.

Context cost

Optimizing SQL loads about 3k tokens when it runs, and up to ~33k if it reads all its reference files. Until then it costs about 62 tokens; SKILL.md has 905 words of instructions outside code blocks.

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

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); files beside SKILL.md are not scanned.

SKILL.md

The full file from ancoleman/ai-design-components at commit 76551b7, republished under its MIT licence (© ancoleman). 905 words, ~2,962 tokens.

Download SKILL.mdSave it as .claude/skills/optimizing-sql/SKILL.md (or your agent's skills folder). This skill also uses 13 other files; get the full folder from GitHub.
name
optimizing-sql
description
Optimize SQL query performance through EXPLAIN analysis, indexing strategies, and query rewriting for PostgreSQL, MySQL, and SQL Server. Use when debugging slow queries, analyzing execution plans, or improving database performance.

SQL Optimization

Provide tactical guidance for optimizing SQL query performance across PostgreSQL, MySQL, and SQL Server through execution plan analysis, strategic indexing, and query rewriting.

When to Use This Skill

Trigger this skill when encountering:

  • Slow query performance or database timeouts
  • Analyzing EXPLAIN plans or execution plans
  • Determining index requirements
  • Rewriting inefficient queries
  • Identifying query anti-patterns (N+1, SELECT *, correlated subqueries)
  • Database-specific optimization needs (PostgreSQL, MySQL, SQL Server)

Core Optimization Workflow

Step 1: Analyze Query Performance

Run execution plan analysis to identify bottlenecks:

PostgreSQL:

sql
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'user@example.com';

MySQL:

sql
EXPLAIN FORMAT=JSON SELECT * FROM products WHERE category_id = 5;

SQL Server: Use SQL Server Management Studio: Display Estimated Execution Plan (Ctrl+L)

Key Metrics to Monitor:

  • Cost: Estimated resource consumption
  • Rows: Number of rows processed (estimated vs actual)
  • Scan Type: Sequential scan vs index scan
  • Execution Time: Actual time spent on operation

For detailed execution plan interpretation, see references/explain-guide.md.

Step 2: Identify Optimization Opportunities

Common Red Flags:

IndicatorProblemSolution
Seq Scan / Table ScanFull table scan on large tableAdd index on filter columns
High row countProcessing excessive rowsAdd WHERE filter or index
Nested Loop with large outer tableInefficient join algorithmIndex join columns
Correlated subquerySubquery executes per rowRewrite as JOIN or EXISTS
Sort operation on large result setExpensive sortingAdd index matching ORDER BY

For scan type interpretation, see references/scan-types.md.

Step 3: Apply Indexing Strategies

Index Decision Framework:

Is column used in WHERE, JOIN, ORDER BY, or GROUP BY?
├─ YES → Is column selective (many unique values)?
│  ├─ YES → Is table frequently queried?
│  │  ├─ YES → ADD INDEX
│  │  └─ NO → Consider based on query frequency
│  └─ NO (low selectivity) → Skip index
└─ NO → Skip index

Index Types by Use Case:

PostgreSQL:

  • B-tree (default): General-purpose, supports <, ≤, =, ≥, >, BETWEEN, IN
  • Hash: Equality comparisons only (=)
  • GIN: Full-text search, JSONB, arrays
  • GiST: Spatial data, geometric types
  • BRIN: Very large tables with naturally ordered data

MySQL:

  • B-tree (default): General-purpose index
  • Full-text: Text search on VARCHAR/TEXT columns
  • Spatial: Spatial data types

SQL Server:

  • Clustered: Table data sorted by index (one per table)
  • Non-clustered: Separate index structure (multiple allowed)

For comprehensive indexing guidance, see references/indexing-decisions.md and references/index-types.md.

Step 4: Design Composite Indexes

For queries filtering on multiple columns, use composite indexes:

Column Order Matters:

  1. Equality filters first (most selective)
  2. Additional equality filters (by selectivity)
  3. Range filters or ORDER BY (last)

Example:

sql
-- Query pattern
SELECT * FROM orders
WHERE customer_id = 123 AND status = 'shipped'
ORDER BY created_at DESC
LIMIT 10;

-- Optimal composite index
CREATE INDEX idx_orders_customer_status_created
ON orders (customer_id, status, created_at DESC);

For composite index design patterns, see references/composite-indexes.md.

Step 5: Rewrite Inefficient Queries

Common Anti-Patterns to Avoid:

1. SELECT * (Over-fetching)

sql
-- ❌ Bad: Fetches all columns
SELECT * FROM users WHERE id = 1;

-- ✅ Good: Fetch only needed columns
SELECT id, name, email FROM users WHERE id = 1;

2. N+1 Queries

sql
-- ❌ Bad: 1 + N queries
SELECT * FROM users LIMIT 100;
-- Then in loop: SELECT * FROM posts WHERE user_id = ?;

-- ✅ Good: Single JOIN
SELECT users.*, posts.id AS post_id, posts.title
FROM users
LEFT JOIN posts ON users.id = posts.user_id;

3. Non-Sargable Queries (functions on indexed columns)

sql
-- ❌ Bad: Function prevents index usage
SELECT * FROM orders WHERE YEAR(created_at) = 2025;

-- ✅ Good: Sargable range condition
SELECT * FROM orders
WHERE created_at >= '2025-01-01' AND created_at < '2026-01-01';

4. Correlated Subqueries

sql
-- ❌ Bad: Subquery executes per row
SELECT name,
  (SELECT COUNT(*) FROM orders WHERE orders.user_id = users.id)
FROM users;

-- ✅ Good: JOIN with GROUP BY
SELECT users.name, COUNT(orders.id) AS order_count
FROM users
LEFT JOIN orders ON users.id = orders.user_id
GROUP BY users.id, users.name;

For complete anti-pattern reference, see references/anti-patterns.md. For efficient query patterns, see references/efficient-patterns.md.

Quick Reference Tables

Index Selection Guide
Query PatternIndex TypeExample
WHERE column = valueSingle-column B-treeCREATE INDEX ON table (column)
WHERE col1 = ? AND col2 = ?Composite B-treeCREATE INDEX ON table (col1, col2)
WHERE text_col LIKE '%word%'Full-text (GIN/Full-text)CREATE INDEX ON table USING GIN (to_tsvector('english', text_col))
WHERE geom && boxSpatial (GiST)CREATE INDEX ON table USING GIST (geom)
WHERE json_col @> '{"key":"value"}'JSONB (GIN)CREATE INDEX ON table USING GIN (json_col)
Join Optimization Checklist
  • Index foreign key columns on both sides of JOIN
  • Order joins starting with table returning fewest rows
  • Use INNER JOIN when possible (more efficient than OUTER JOIN)
  • Avoid joining more than 5 tables (break into CTEs or subqueries)
  • Consider denormalization for frequently joined tables in read-heavy systems
Execution Plan Performance Targets
Scan TypePerformanceWhen Acceptable
Index-Only ScanBestAlways preferred
Index ScanExcellentSmall-medium result sets
Bitmap Heap ScanGoodMedium result sets (PostgreSQL)
Sequential ScanPoorOnly for small tables (<1000 rows) or full table queries
Table ScanPoorOnly for small tables or unavoidable full scans
Show full SKILL.md (357 more words)Show less

Database-Specific Optimizations

PostgreSQL-Specific Features

Partial Indexes (index subset of rows):

sql
CREATE INDEX idx_active_users_login
ON users (last_login)
WHERE status = 'active';

Expression Indexes (index computed values):

sql
CREATE INDEX idx_users_email_lower
ON users (LOWER(email));

Covering Indexes (avoid heap access):

sql
CREATE INDEX idx_users_email_covering
ON users (email) INCLUDE (id, name);

For comprehensive PostgreSQL optimization, see references/postgresql.md.

MySQL-Specific Features

Index Hints (override optimizer):

sql
SELECT * FROM orders USE INDEX (idx_orders_customer)
WHERE customer_id = 123;

Storage Engine Selection:

  • InnoDB (default): Transactional, row-level locks, clustered primary key
  • MyISAM: Faster reads, no transactions, table-level locks

For comprehensive MySQL optimization, see references/mysql.md.

SQL Server-Specific Features

Query Store (track query performance over time):

sql
ALTER DATABASE YourDatabase SET QUERY_STORE = ON;

Execution Plan Warnings:

  • Look for yellow exclamation marks in graphical execution plans
  • Thick arrows indicate high row counts

For comprehensive SQL Server optimization, see references/sqlserver.md.

Advanced Optimization Techniques

Common Table Expressions (CTEs)

Break complex queries into readable, maintainable parts:

sql
WITH active_customers AS (
  SELECT id, name FROM customers WHERE status = 'active'
),
recent_orders AS (
  SELECT customer_id, COUNT(*) as order_count
  FROM orders
  WHERE created_at > NOW() - INTERVAL '30 days'
  GROUP BY customer_id
)
SELECT ac.name, COALESCE(ro.order_count, 0) as orders
FROM active_customers ac
LEFT JOIN recent_orders ro ON ac.id = ro.customer_id;
EXISTS vs IN for Subqueries

Use EXISTS for better performance with large datasets:

sql
-- ✅ Good: EXISTS stops at first match
SELECT * FROM users
WHERE EXISTS (SELECT 1 FROM orders WHERE orders.user_id = users.id);

-- ❌ Less efficient: IN builds full list
SELECT * FROM users
WHERE id IN (SELECT user_id FROM orders);
Denormalization Decision Framework

Consider denormalization when:

  • Query joins 3+ tables frequently
  • Data is relatively static (infrequent updates)
  • Read performance is critical
  • Write overhead is acceptable

Denormalization Strategies:

  1. Duplicate columns: Copy foreign key data into main table
  2. Summary tables: Pre-aggregate data
  3. Materialized views: Database-maintained denormalized views
  4. Application caching: Redis/Memcached for frequently accessed data

Optimization Workflow Example

Scenario: API endpoint taking 2 seconds to load

Step 1: Identify Slow Query

Use APM/observability tools to identify database query causing delay

Step 2: Run EXPLAIN ANALYZE

sql
EXPLAIN ANALYZE SELECT * FROM orders
WHERE customer_id = 123
ORDER BY created_at DESC
LIMIT 10;

Step 3: Analyze Output

Seq Scan on orders (cost=0.00..2500.00 rows=10)
  Filter: (customer_id = 123)
  Rows Removed by Filter: 99990

Problem: Sequential scan filtering 99,990 rows

Step 4: Add Composite Index

sql
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);

Step 5: Verify Improvement

sql
EXPLAIN ANALYZE SELECT * FROM orders
WHERE customer_id = 123
ORDER BY created_at DESC
LIMIT 10;
Index Scan using idx_orders_customer_created (cost=0.42..12.44 rows=10)
  Index Cond: (customer_id = 123)

Result: 200x faster (2000ms → 10ms)

Monitoring and Maintenance

Regular Optimization Tasks:

  • Review slow query logs weekly
  • Update database statistics regularly (ANALYZE in PostgreSQL, UPDATE STATISTICS in SQL Server)
  • Monitor index usage (drop unused indexes)
  • Archive old data to keep tables manageable
  • Review execution plans for critical queries quarterly

PostgreSQL Statistics Update:

sql
ANALYZE table_name;

MySQL Statistics Update:

sql
ANALYZE TABLE table_name;

SQL Server Statistics Update:

sql
UPDATE STATISTICS table_name;
  • databases-relational: Schema design and database fundamentals
  • observability: Performance monitoring and slow query detection
  • api-patterns: API-level optimization (pagination, caching)
  • performance-engineering: Application performance profiling

Additional Resources

For comprehensive documentation, reference these files:

  • references/explain-guide.md - Detailed EXPLAIN plan interpretation
  • references/scan-types.md - Scan type meanings and performance implications
  • references/indexing-decisions.md - When and how to add indexes
  • references/index-types.md - Database-specific index types
  • references/composite-indexes.md - Multi-column index design
  • references/anti-patterns.md - Common anti-patterns with solutions
  • references/efficient-patterns.md - Efficient query patterns
  • references/postgresql.md - PostgreSQL-specific optimizations
  • references/mysql.md - MySQL-specific optimizations
  • references/sqlserver.md - SQL Server-specific optimizations

For working SQL examples, see examples/ directory.

© ancoleman, 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 13 other files (references) in skills/optimizing-sql of ancoleman/ai-design-components.

  • SKILL.md
  • examples/explain-analysis-examples.sql
  • examples/query-rewriting-examples.sql
  • outputs.yaml
  • references/anti-patterns.md
  • references/composite-indexes.md
  • references/efficient-patterns.md
  • references/explain-guide.md
  • references/index-types.md
  • references/indexing-decisions.md
  • references/mysql.md
  • references/postgresql.md
  • references/scan-types.md
  • references/sqlserver.md

Open the folder on GitHubat commit 76551b7

Compare with similar skills

Optimizing SQL 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 compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Optimizing SQL this skillancoleman/ai-design-components526—~3kAutomated safety check: PassMIT
SQL ProJeffallan/claude-skills12k—~1.3kAutomated safety check: PassMIT
SQL Optimizationgithub/awesome-copilot40k2 repos~2.3kAutomated safety check: PassMIT
Agent SQL Proxiaoyuge886/aigc198—~315Automated safety check: PassMIT
SQL Expertaiskillstore/marketplace430—~3.4kAutomated safety check: PassNone
SQL MasterFerroxLabs/wayland608—~4kAutomated 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
  • 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
  • SQL Expert

    aiskillstore/marketplace

    Expert SQL query writing, optimization, and database schema design with support for PostgreSQL, MySQL, SQLite, and SQL Server.

    430 GitHub stars~3.4k tokensUpdated today
    DatabasesAuto-check passed
  • SQL Master

    FerroxLabs/wayland

    Advanced SQL expertise including window functions, CTEs, recursive queries, query optimization with EXPLAIN plans, indexing strategies, pivot/unpivot operations, JSON operations, full-text search…

    608 GitHub stars~4k tokensUpdated yesterday
    DatabasesAuto-check passed
  • Database Migrations SQL Migrations

    rmyndharis/antigravity-skills

    SQL database migrations with zero-downtime strategies for PostgreSQL, MySQL, SQL Server

    1.7k GitHub starsUsed in 2 repos~577 tokens
    DatabasesAuto-check: notes

More from ancoleman/ai-design-components

All 75 skills in this repo
  • Building AI Chat

    ancoleman/ai-design-components

    Builds AI chat interfaces and conversational UI with streaming responses, context management, and multi-modal support.

    526 GitHub starsUsed in 1 repo~3.4k tokens
    Auto-check passed
  • Building Forms

    ancoleman/ai-design-components

    Builds form components and data collection interfaces including contact forms, registration flows, checkout processes, surveys, and settings pages.

    526 GitHub stars~3.7k tokensUpdated 10 mo ago
    Auto-check passed
  • Building Tables

    ancoleman/ai-design-components

    Builds tables and data grids for displaying tabular information, from simple HTML tables to complex enterprise data grids.

    526 GitHub stars~1.8k tokensUpdated 10 mo ago
    Auto-check passed
  • Creating Dashboards

    ancoleman/ai-design-components

    Creates comprehensive dashboard and analytics interfaces that combine data visualization, KPI cards, real-time updates, and interactive layouts.

    526 GitHub stars~3.5k tokensUpdated 10 mo ago
    Auto-check passed
  • Designing Layouts

    ancoleman/ai-design-components

    Designs layout systems and responsive interfaces including grid systems, flexbox patterns, sidebar layouts, and responsive breakpoints.

    526 GitHub stars~1.7k tokensUpdated 10 mo ago
    Auto-check passed
  • Displaying Timelines

    ancoleman/ai-design-components

    Displays chronological events and activity through timelines, activity feeds, Gantt charts, and calendar interfaces.

    526 GitHub stars~2.7k tokensUpdated 10 mo ago
    Auto-check passed

Categories

Questions about Optimizing SQL

What does Optimizing SQL do?

Optimize SQL query performance through EXPLAIN analysis, indexing strategies, and query rewriting for PostgreSQL, MySQL, and SQL Server. Optimizing SQL is an agent skill from ancoleman/ai-design-components. Optimize SQL query performance through EXPLAIN analysis, indexing strategies, and query rewriting for PostgreSQL, MySQL, and SQL Server.

When should I use Optimizing SQL?

Optimizing SQL fits situations like: debugging slow queries; analyzing execution plans; improving database performance.

How do I install Optimizing SQL in Claude Code?

Run `npx skills add ancoleman/ai-design-components --skill optimizing-sql -a claude-code`. Or copy the skill folder (skills/optimizing-sql in ancoleman/ai-design-components) into .claude/skills/optimizing-sql in your project. Claude Code loads it when a task matches its description.

How do I install Optimizing SQL in Codex?

Run `npx skills add ancoleman/ai-design-components --skill optimizing-sql -a codex`. Or copy the skill folder (skills/optimizing-sql in ancoleman/ai-design-components) into .agents/skills/optimizing-sql in your project. Codex loads it when a task matches its description.

Can I use Optimizing SQL 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 ancoleman/ai-design-components --skill optimizing-sql -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, .gemini/skills/optimizing-sql, .github/skills/optimizing-sql and .opencode/skills/optimizing-sql in your project.

What does Optimizing SQL need to run?

SKILL.md names no scripts, command-line tools or credentials: Optimizing SQL is instructions for the agent only.

Does Optimizing SQL access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Optimizing SQL 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. Review the folder before installing.

What licence does Optimizing SQL use?

Optimizing SQL is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Optimizing SQL use?

About 3k tokens (SKILL.md is roughly 12k 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 30k tokens, read only when the agent opens those files.

What are the alternatives to Optimizing SQL?

Skills that share tags, products or a category with Optimizing SQL: SQL Pro (Jeffallan/claude-skills, 12k stars), SQL Optimization (github/awesome-copilot, 40k stars), Agent SQL Pro (xiaoyuge886/aigc, 198 stars) and SQL Expert (aiskillstore/marketplace, 430 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Optimizing SQL?

ancoleman (a GitHub user) maintains it in ancoleman/ai-design-components, which has 526 GitHub stars. The repository holds 75 skills in this directory. The repository was last updated on December 11, 2025.

Source: ancoleman/ai-design-components on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.