- Home
- Skills
- Data & Databases
- SQL Query Clinic: Correct & Fast Queries
Works with the AI Agents you already use
SQL Query Clinic: Correct & Fast Queries
Write, explain, debug and speed up SQL for Postgres, MySQL, SQLite, SQL Server, BigQuery, Snowflake and ClickHouse: joins, CTEs, window functions, EXPLAIN plans, index design and rewrites with before/after timings.
Free
SQL Query Clinic: Correct & Fast Queries
Example session with this skill installed
This query on my Postgres v15 orders table is taking 8 seconds. Here is the query and the EXPLAIN (ANALYZE, BUFFERS) output. How do I fix it?
- Read your context and instructions
- Compiled the sql query clinic
I have analyzed your query and execution plan. The bottleneck is a Seq Scan on the `orders` table because the `created_at` filter is wrapped in a `DATE()` function, which prevents the index from being used. Additionally, the nested loop join is spilling to disk due to a low `work_mem` setting relative to the row count. ## Optimization Report | Metric | Before | After (Estimated) | Improvement | | :--- | :--- | :--- | :--- | | Execution Time | 8.24s | 0.12s | ~68x faster | | Buffers (Read) | 450,231 | 1,204 | 99.7% reduction | | Plan Node | Seq Scan | Index Only Scan | - | ### Optimized Query ```sql -- Use half-open range to allow index usage on created_at timestamp SELECT u.email, COUNT(o.id) as order_count, SUM(o.total_amount) as lifetime_value FROM users u JOIN orders o ON u.id = o.user_id WHERE o.created_at >= '2023-01-01' AND o.created_at < '2024-01-01' AND o.status = 'completed' GROUP BY u.email HAVING COUNT(o.id) > 5; ``` ### Recommended Index ```sql -- Composite index supporting the filter and the join key CREATE INDEX CONCURRENTLY idx_orders_performance_triage ON orders (created_at, status, user_id) WHERE status = 'completed'; ``` **Next steps** 1. Run the `CREATE INDEX CONCURRENTLY` statement during a low-traffic window. 2. Update table statistics by running `ANALYZE orders;`. 3. Check if `work_mem` can be increased for this session if the sort still spills.
Connects securely to your tools. The creator never sees your data.
About this skill
Database performance issues often stem from inefficient joins, missing indexes, or poor query structure. This skill diagnoses slow SQL and writes optimized queries for major engines including PostgreSQL, MySQL, BigQuery, and Snowflake. ## What it does - **Query generation** converts natural language questions into valid SQL using CTEs, window functions, and proper join logic. - **Performance profiling** analyzes `EXPLAIN ANALYZE` output to identify sequence scans, disk spills, and row estimate mismatches. - **Index design** recommends composite, covering, or partial indexes based on predicate ordering and write costs. - **Logic debugging** catches common pitfalls like NULL handling in `NOT IN` clauses, Cartesian products, and time zone errors. - **Sargability optimization** rewrites queries to ensure filters use existing indexes by removing functions on indexed columns. ## How it works 1. **Schema discovery** involves identifying the engine, table structures, and row counts to establish context. 2. **Drafting** produces readable SQL using CTEs and explicit column lists while checking for row multiplication. 3. **Diagnosis** reads execution plans to find bottlenecks like nested loops over large datasets or full table scans. 4. **Optimization** applies rewrites, index recommendations, or structural changes like partitioning. 5. **Validation** compares before and after timings and row counts to ensure correctness and speed. ## Frameworks & tools Supports PostgreSQL, MySQL/MariaDB, SQLite, SQL Server (T-SQL), Google BigQuery, Snowflake, and ClickHouse. ## Why this beats prompting it yourself Generic prompts often ignore engine-specific execution plan nuances or produce queries that "look" right but fail on NULL handling. This skill systematically analyzes execution plans to provide evidence-based optimizations rather than guessing. ## Use cases - Optimizing a slow dashboard query that is timing out in production. - Converting complex business logic into efficient window functions or CTEs. - Identifying why an index is being ignored by the query planner. - Refactoring deep `OFFSET` pagination into high-performance keyset pagination. ## Known limitations Requires table schemas or `CREATE TABLE` statements to generate accurate queries. Avoids running DDL like index creation on production environments without explicit confirmation.
Requires schemas and engine version for accuracy. DDL execution like index creation requires user confirmation. Execution plan analysis requires the user to provide plan output.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before any payment.
Reviews
This skill has been used 7 times.
Trust & safety
Security scan
Security scan passed 7 days ago
- Free with an Agensi account
Permissions
No special permissions declared or detected