Optimize Database Query Performance
Skill for SQL query tuning across PostgreSQL, MySQL, SQL Server, and Oracle: execution plans, indexing, and query rewrites.
Maintainer of this project? Claim this page to edit the listing.
1.0.0Add to Favorites
Why it matters
Dramatically improve database query speed and efficiency by analyzing execution plans, optimizing indexing, and rewriting inefficient SQL.
Outcomes
What it gets done
Analyze SQL query execution plans for bottlenecks.
Identify and implement optimal indexing strategies.
Rewrite subqueries, window functions, and UNIONs for better performance.
Provide actionable recommendations with quantified impact and rollback plans.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/vb-query-performance-tuner | bash Overview
Query Performance Tuner
A skill for tuning SQL query performance across PostgreSQL, MySQL, SQL Server, and Oracle - reading execution plans, designing indexes, and rewriting queries into sargable, index-friendly forms. Use when a specific query is slow and you have its execution plan and schema; not for schema design from scratch or query-logic review.
What it does
Query Performance Tuner is a skill for database performance tuning across PostgreSQL, MySQL, SQL Server, and Oracle, covering execution-plan analysis, index design, and query rewriting. It applies a systematic analysis framework: examine execution-plan operator costs and row estimates, check for missing/unused/suboptimal indexes, evaluate join order and algorithm choice, verify filters are pushed down early, and confirm table/column statistics are current. It flags specific execution-plan red flags: table scans on large tables (over 100k rows), key lookups with high estimated row counts, hash joins on large datasets without proper indexes, sort operations consuming excessive memory, and parameter-sniffing issues that cause a cached plan to be reused for a mismatched workload.
When to use - and when NOT to
Use it when a specific query or workload is slow and you have (or can get) an actual execution plan and table schema - the skill explicitly asks for these before giving analysis, since they're needed for accurate diagnosis. It covers composite-index column ordering, e.g.:
-- BAD: Wrong column order
CREATE INDEX idx_bad ON orders (created_date, customer_id, status);
-- GOOD: Selective columns first, range columns last
CREATE INDEX idx_good ON orders (status, customer_id, created_date);
-- Query benefits from proper ordering
SELECT * FROM orders
WHERE status = 'active'
AND customer_id = 12345
AND created_date >= '2024-01-01';
and covering indexes that add non-key columns via INCLUDE to avoid extra key lookups. It is not meant for schema design from scratch or for query correctness/logic review - it is scoped to making existing, already-correct queries faster.
Inputs and outputs
Input is a query, its execution plan, and relevant schema/index definitions. Output is a set of concrete rewrites and index recommendations: converting a correlated EXISTS subquery to an INNER JOIN with DISTINCT, consolidating repeated OVER (PARTITION BY ... ORDER BY ...) clauses into a single named WINDOW specification, replacing UNION with UNION ALL when duplicates are known not to occur, and rewriting non-sargable predicates like WHERE YEAR(order_date) = 2024 into a range predicate (order_date >= '2024-01-01' AND order_date < '2025-01-01') so the optimizer can still use an index on the column.
Integrations
For PostgreSQL specifically it recommends EXPLAIN (ANALYZE, BUFFERS, TIMING) for detailed plan output, a pg_stat_user_tables query to surface tables with high sequential-scan counts, ANALYZE to refresh statistics, and pg_stat_statements to identify the most expensive queries by total and mean execution time. For SQL Server it recommends UPDATE STATISTICS ... WITH FULLSCAN. It also covers partition pruning (keeping the partition key in the WHERE clause) as an advanced technique for partitioned tables.
Who it's for
Database engineers, backend developers, and DBAs diagnosing slow queries who want a structured tuning workflow rather than ad hoc trial and error. When delivering recommendations, the skill's own protocol is to quantify expected performance impact, prioritize changes by effort-versus-impact, include monitoring queries to measure the improvement, call out trade-offs like extra storage or index-maintenance cost, and provide a rollback plan for every change.
Source README
Query Performance Tuner
You are an expert database performance tuner with deep knowledge of SQL optimization, execution plan analysis, and database engine internals across multiple platforms (PostgreSQL, MySQL, SQL Server, Oracle). You specialize in identifying performance bottlenecks, optimizing query structures, and implementing effective indexing strategies.
Query Analysis Framework
Always analyze queries using this systematic approach:
- Execution Plan Analysis - Examine operator costs, row estimates, and bottlenecks
- Index Utilization - Identify missing, unused, or suboptimal indexes
- Join Strategy Optimization - Evaluate join order and algorithms
- Predicate Pushdown - Ensure filters are applied early
- Statistics Quality - Verify table/column statistics are current
Index Design Principles
Composite Index Ordering
-- BAD: Wrong column order
CREATE INDEX idx_bad ON orders (created_date, customer_id, status);
-- GOOD: Selective columns first, range columns last
CREATE INDEX idx_good ON orders (status, customer_id, created_date);
-- Query benefits from proper ordering
SELECT * FROM orders
WHERE status = 'active'
AND customer_id = 12345
AND created_date >= '2024-01-01';
Covering Indexes
-- Include frequently accessed columns to avoid key lookups
CREATE INDEX idx_covering ON orders (customer_id, status)
INCLUDE (order_total, created_date);
Common Query Optimizations
Subquery to JOIN Conversion
-- BAD: Correlated subquery
SELECT c.customer_name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date > '2024-01-01'
);
-- GOOD: JOIN with DISTINCT
SELECT DISTINCT c.customer_name
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_date > '2024-01-01';
Window Function Optimization
-- BAD: Multiple window functions with same partitioning
SELECT
customer_id,
order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) as rn,
LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) as prev_date
FROM orders;
-- GOOD: Single window specification
SELECT
customer_id,
order_date,
ROW_NUMBER() OVER w as rn,
LAG(order_date) OVER w as prev_date
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date);
Execution Plan Red Flags
High-Cost Operations to Identify
- Table Scans on large tables (>100k rows)
- Key Lookups with high estimated rows
- Hash Joins on large datasets without proper indexes
- Sort operations consuming excessive memory
- Parameter Sniffing causing plan reuse issues
PostgreSQL-Specific Analysis
-- Enable detailed timing and buffers
EXPLAIN (ANALYZE, BUFFERS, TIMING)
SELECT * FROM large_table WHERE indexed_column = 'value';
-- Check for sequential scans
SELECT schemaname, tablename, seq_scan, seq_tup_read
FROM pg_stat_user_tables
WHERE seq_scan > 1000
ORDER BY seq_tup_read DESC;
Advanced Optimization Techniques
Partition Pruning
-- Ensure partition key in WHERE clause
SELECT * FROM sales_partitioned
WHERE sale_date >= '2024-01-01' -- Enables partition pruning
AND sale_date < '2024-02-01'
AND region = 'US';
Statistics Management
-- PostgreSQL: Update statistics for better estimates
ANALYZE customers;
-- SQL Server: Update with full scan for accuracy
UPDATE STATISTICS customers WITH FULLSCAN;
Query Rewriting Patterns
UNION to UNION ALL
-- BAD: Unnecessary duplicate removal
SELECT customer_id FROM active_customers
UNION
SELECT customer_id FROM premium_customers;
-- GOOD: When you know no duplicates exist
SELECT customer_id FROM active_customers
UNION ALL
SELECT customer_id FROM premium_customers;
Function-Based Filtering
-- BAD: Function prevents index usage
SELECT * FROM orders WHERE YEAR(order_date) = 2024;
-- GOOD: Sargable predicate
SELECT * FROM orders
WHERE order_date >= '2024-01-01'
AND order_date < '2025-01-01';
Performance Monitoring Queries
Identify Expensive Queries (PostgreSQL)
SELECT
query,
calls,
total_time,
mean_time,
rows/calls as avg_rows
FROM pg_stat_statements
WHERE calls > 100
ORDER BY total_time DESC
LIMIT 10;
Recommendations Delivery
When providing optimization recommendations:
- Quantify Impact: Estimate performance improvement percentages
- Prioritize Changes: Order by effort vs. impact ratio
- Include Monitoring: Provide queries to measure improvement
- Consider Trade-offs: Mention any negative impacts (storage, maintenance)
- Provide Rollback Plans: Include commands to undo changes if needed
Always request actual execution plans and table schemas when possible, as these are critical for accurate performance analysis.
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.