Database query optimizer
Welcome to the skill-jam βοΈπ
npx -y skills add VRIL-LABS/skill-jam --skill database-query-optimizerAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its author says it does
Copied from the file, not written here
Analyzes SQL or NoSQL queries, explains query plans, and rewrites them for better performance. Invoke when asked to optimize a query, speed up a slow database call, analyze a query plan, add indexes, or fix N+1 query problems.
SKILL.md
5.4 KB, ~1.2k tokens by cl100k_base, as published. Nobody here has run it
Database Query Optimizer
Analyzes SQL and NoSQL queries for performance bottlenecks, interprets query execution plans, and rewrites queries or proposes schema/index changes to reduce latency and resource usage.
When to Use
- User shares a slow query or reports high database latency
EXPLAIN/EXPLAIN ANALYZEoutput shows sequential scans, hash joins on large tables, or high cost estimates- Application performance profiling identifies database calls as the bottleneck
- An ORM is generating N+1 queries
- User asks to add indexes to improve query performance
- A query times out in production under load
Process
-
Understand the query context:
- What database engine? (PostgreSQL, MySQL, SQLite, MongoDB, DynamoDB, etc.)
- What is the approximate table size and cardinality of key columns?
- Are there existing indexes? (request
\d tablenameorSHOW INDEX FROM tablenameif not provided) - What is the acceptable latency target?
-
Parse and analyze the query:
- Identify which tables are scanned and which are indexed lookups
- Look for
SELECT *β replace with explicit column list - Find unindexed filter columns in
WHERE,JOIN ON, andORDER BYclauses - Spot functions applied to indexed columns (
WHERE LOWER(email) = ...) that defeat indexes - Identify correlated subqueries that execute once per row
- Check for
DISTINCTorGROUP BYon large result sets without filtering first - Look for
OFFSET-based pagination on large tables (use keyset pagination instead)
-
Read and interpret the query plan (if provided):
Seq Scanon a large table β missing indexHash Joinwith high rows β consider indexed nested loop join- High
actual timevsestimated rowsβ stale statistics, runANALYZE Sortnode with high cost β add index that provides sort orderNested Loopwith large outer table β may need to rewrite as CTE or temp table
-
Propose optimizations in priority order:
- Index additions: most impactful, lowest risk
- Query rewrite: equivalent logic, better plan
- Schema changes: denormalization, partitioning (higher effort, note trade-offs)
- Application-level: batching, caching, connection pooling
-
Write the optimized query and explain the improvement.
-
Suggest the index DDL with justification.
-
Estimate the improvement based on query plan changes (e.g., "reduces rows scanned from 500k to ~200").
Output Format
## Query Analysis
### Original Query
```sql
SELECT DISTINCT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE LOWER(u.email) LIKE '%@example.com'
GROUP BY u.name
ORDER BY order_count DESC;
Issues Found
- Function on indexed column (
LOWER(u.email)) β prevents index use onemail. - Leading wildcard in LIKE (
'%@example.com') β forces full table scan. - SELECT DISTINCT + GROUP BY is redundant β DISTINCT can be removed.
- No index on
orders.user_idβ the JOIN causes a sequential scan oforders.
Optimized Query
SELECT u.name, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.email ILIKE '%@example.com' -- or store domain separately
GROUP BY u.id, u.name
ORDER BY order_count DESC;
Recommended Indexes
-- Enables fast join on orders table
CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);
-- For domain-based filtering, consider a generated column:
ALTER TABLE users ADD COLUMN email_domain TEXT GENERATED ALWAYS AS
(split_part(email, '@', 2)) STORED;
CREATE INDEX idx_users_email_domain ON users(email_domain);
Expected Improvement
idx_orders_user_idreduces JOIN cost from Seq Scan (O(n)) to Index Scan (O(log n))- Estimated query time: 2400ms β ~80ms for typical dataset of 100k users / 2M orders
## Examples
### Example Input (N+1 Problem)
```python
# ORM generating N+1 queries
users = User.objects.all()
for user in users:
print(user.profile.bio) # triggers 1 query per user
Example Output
# Fix: use select_related to JOIN in a single query
users = User.objects.select_related('profile').all()
for user in users:
print(user.profile.bio) # no additional queries
# SQL generated (1 query instead of N+1):
# SELECT users.*, profiles.* FROM users
# INNER JOIN profiles ON profiles.user_id = users.id
Boundaries
- Do NOT suggest schema changes (adding columns, partitioning) without explicitly noting the migration effort and potential downtime.
- Do NOT recommend
CREATE INDEXwithoutCONCURRENTLYon production PostgreSQL tables β blocking locks can cause outages. - Do NOT assume cardinality or data distribution β ask if needed for accurate advice.
- Do NOT rewrite stored procedures or triggers unless explicitly asked.
- If the query plan is not provided, flag that recommendations are based on static analysis only and may not reflect actual execution behavior.
- Do NOT recommend disabling query planner features (e.g.,
enable_seqscan = off) as a production fix. - NoSQL (MongoDB, DynamoDB) optimization follows different principles β confirm the query type before applying SQL-specific advice.
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.