query-optimization
Skill4 starsChanged 4 months agoMITView on GitHub
Find and fix slow SQL — read the slow query log and EXPLAIN, add the right indexes, rewrite non-sargable and over-fetching queries, and cache what is genuinely hot. Use when the user needs to rewrite a query — remove a function on a column, replace OFFSET paging, avoid SELECT *, or add caching — so it runs efficiently; the user has a slow request or report where profiling points at the database, and wants to find and speed up the offending query; the user wants to enable and read the MySQL slow query log (or performance_schema) to find the queries costing the most total time. Keywords: query-optimization, performance, sql, slow-query, explain, indexing, caching, pagination, database.
9 other projects use a version of this.
Adopted by
Most recently taken up by
- Indium-AI-Labs/indium-agentkittheir own version, first seen Nov 1, 2026
- jars-demo/jars-skillstheir own version, first seen Oct 25, 2026
- Ionate-Technologies/indium-agentkittheir own version, first seen Oct 20, 2026
- duyet/clickhouse-monitoringtheir own version, first seen Oct 8, 2026
- nahid-sparktales/agent-dispatchertheir own version, first seen Sep 21, 2026
- novatic-cu/nova-skillstheir own version, first seen Sep 20, 2026
Used with
Projects with it also use background-jobs, product-analytics and 1 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
YepAPISkillbackground-jobs
Queue workers with BullMQ/Inngest/Trigger.dev, job retries, dead letter queues, concurrency.
Also in 3 projects that use this
SkeneTechnologiesSkillproduct-analytics
When the user wants to set up product analytics -- including event taxonomy, tracking plans, funnel analysis, or tool selection (Mixpanel, Amplitude, PostHog). Also use when the user says "event tracking," "analytics setup," "tracking plan," "analytics implementation," or "user identification." For PLG metrics, see plg-metrics. For experimentation, see growth-experimentation.
Also in 4 projects that use this
SentrySkillsecurity-review
Finds exploitable application security vulnerabilities in code changes. Use for Warden security scans, appsec review, OWASP-style checks, authentication or authorization bugs, injection, XSS, SSRF, path traversal, secrets, unsafe crypto, webhook verification, open redirects, or sensitive data exposure.
Also in 3 projects that use this
Other versions9 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 9
- duyet/clickhouse-monitoring★ 303same name
- nahid-sparktales/agent-dispatcher★ 59same name
- Indium-AI-Labs/indium-agentkit★ 18same name
- Ionate-Technologies/indium-agentkit★ 17same name
- ffsshhttiikk/opencode-agents-skills★ 2same name
- novatic-cu/nova-skills★ 1same name
- Abdox-menara/guard-skills★ 0same name
- gclm/super-stack★ 0same name
- jars-demo/jars-skills★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository119 other files it gives its agents.
- strategy-bitrix-d7-incrementalSkill
- strategy-explicit-over-magicSkill
- strategy-framework-conventionsSkill
- strategy-legacy-safe-editsSkill
- strategy-minimal-diffSkill
- strategy-no-untested-refactorSkill
- strategy-preserve-public-apiSkill
- strategy-readonly-immutabilitySkill
- strategy-security-firstSkill
- strategy-test-drivenSkill
- openapiSkill
- paginationSkill
- rest-designSkill
- versioningSkill
- cqrsSkill
- dependency-inversionSkill
- hexagonalSkill
- repository-patternSkill
- service-layerSkill
- bitrixSkill
- findings-reportSkill
- laravelSkill
- performanceSkill
- phpSkill
- project-analysisSkill
- refactoringSkill
- roi-prioritizationSkill
- securitySkill
- stack-detectionSkill
- cache-layersSkill
- component-engineSkill
- d7-eventsSkill
- d7-loaderSkill
- d7-orm-queriesSkill
- iblock-elementsSkill
- kernel-main-moduleSkill
- localizationSkill
- controllersSkill
- ormSkill
- validationSkill
- controllersSkill
- query-builderSkill
- routingSkill
- autoload-psr4Skill
- dependency-managementSkill
- scriptsSkill
- connection-poolingSkill
- mysql-indexingSkill
- redisSkill
- transactionsSkill
- ci-github-actionsSkill
- deployment-strategiesSkill
- docker-phpSkill
- env-configSkill
- associationsSkill
- entities-mappingSkill
- orm-basicsSkill
- entity-apiSkill
- module-developmentSkill
- routing-controllersSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 7 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 68
Do not optimize queries when profiling shows the time is in PHP CPU, serialization, or an external API, not in database wait.
- Distinctive: line 70
Do not hand-tune queries that are already fast and infrequent just because they could theoretically be faster.
“Common” is measured: kept by at least 6 in 10 of the 7 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
<!-- generated: do not edit — source: knowledge/atoms/performance/query-optimization/ --><!-- schema: atomVersion=3 skillVersion=2 graphVersion=1 --><!-- compile: @php-skills/compiler v1.0.0 (deterministic build) -->SQL Query Optimization
When to use
- The user needs to rewrite a query — remove a function on a column, replace OFFSET paging, avoid SELECT *, or add caching — so it runs efficiently.
- The user has a slow request or report where profiling points at the database, and wants to find and speed up the offending query.
- The user wants to enable and read the MySQL slow query log (or performance_schema) to find the queries costing the most total time.
When NOT to use
- Do not optimize queries when profiling shows the time is in PHP CPU, serialization, or an external API, not in database wait.
- Do not hand-tune queries that are already fast and infrequent just because they could theoretically be faster.
Core guidance
- EXPLAIN the query, then add the index it needs — Run EXPLAIN on the slow query; if
typeisALLorrowsis large, add a composite index covering the WHERE, JOIN, and ORDER BY columns in leftmost-prefix order, then re-EXPLAIN to confirm the plan improved. - Measure before optimizing, then target the worst query — Start from data: enable the slow query log or read performance_schema, rank queries by total time (frequency x duration), and optimize the top offender first — never guess which query is slow.
Quick recipe
- Enable the slow query log (or read performance_schema), aggregate with a tool like pt-query-digest, and pick the query with the highest total time. (verify: You have one specific slow statement ranked by frequency x duration.)
- EXPLAIN the query against production-scale data; add a composite/covering index
for a scan, make predicates sargable, trim
SELECT *, and replace deep OFFSET paging with keyset paging. (verify: EXPLAINtypeimproves toref/range,rowsdrops sharply, and no filesort remains.) - Re-run the workload and confirm latency and rows-examined dropped. If the now-lean query is still hot, add a TTL cache with jitter and single-flight protection; otherwise stop. (verify: Measured p95 latency for the query fell and, if cached, a cache miss no longer stampedes the database.)
Best practices
- Collapse a loop of single-row INSERT/UPDATE/SELECT into one set-based statement
(multi-row INSERT,
WHERE id IN (...), or a JOIN update) to cut network round-trips - Once a query is indexed and rewritten, cache the result (Redis/APCu) only for reads that are hot and tolerate slight staleness, always with a TTL and an invalidation-on-write path
- Replace
LIMIT ? OFFSET Non large tables with keyset (seek) pagination —WHERE id < ? ORDER BY id DESC LIMIT ?— so deep pages do not scan and discard N rows - Replace
SELECT *with the explicit columns the code reads, so the query can be covered by an index and transfers less data over the wire
Anti-patterns
| Anti-pattern | Why it fails | Do instead |
| Running COUNT(*) over a huge table for every page | An exact count scans the whole matching set, often costing more than fetching the page itself. | Use keyset pagination without a total, show an approximate count (e.g. from<br>information_schema or a cached estimate), or a "load more" UI that needs no total. |
| Optimizing by guesswork instead of the slow log | The bottleneck is rarely where intuition says; only the slow log or profiler shows the real cost. | Enable the slow query log or performance_schema, rank by total time, and optimize<br>the measured top offender. |
| Scaling hardware to hide a missing index | A missing index makes cost grow with data, so scaling up only delays the same wall at higher spend. | EXPLAIN the query and add the correct index or rewrite it before considering a<br>larger instance. |
See references/anti-patterns.md.
Common mistakes
- Caching masks a slow query until the cache misses — Wrapping a slow, unindexed query in a cache makes warm requests fast but leaves every cold start, deploy, or invalidation exposed to the full slow query — often a thundering herd. Fix: Fix the query (index, rewrite) first, then cache; on top, add TTL jitter and a single-flight lock so a miss cannot stampede the database.
- EXPLAIN on an empty or tiny table misleads you — Running EXPLAIN against a dev database with a handful of rows shows a fast plan
even when production with millions of rows will pick a different, slow plan. Fix: Test EXPLAIN against production-scale data (a copy or realistic seed) and run
ANALYZE TABLEso statistics reflect real cardinality. - OFFSET pagination gets slower the deeper you page —
LIMIT 20 OFFSET 100000must read and discard 100,000 rows before returning 20, so page latency grows linearly with page number even with an index. Fix: Switch to keyset/seek pagination on an indexed, ordered column (WHERE id < :lastId ORDER BY id DESC LIMIT 20) so each page seeks directly. - OR across different columns can defeat the index — A predicate like
WHERE email = ? OR phone = ?often cannot use a single index and falls back to a full scan, even when both columns are individually indexed. Fix: Rewrite as aUNIONof two indexed single-column queries, or add an index the optimizer can use via index merge, and confirm with EXPLAIN.
Version notes
- EXPLAIN ANALYZE and better optimizer tools in MySQL 8 (PHP >=7.4) — MySQL 8.0 adds
EXPLAIN ANALYZE(real measured execution), a cost-based optimizer trace, and hash joins; MySQL 5.7 offers only estimate-based EXPLAIN and no hash join.performance_schemaslow-query data is available on both.
Security
- Optimize with bound parameters and allow-listed sort columns — When rewriting queries for speed, keep every user value bound as a parameter and validate any dynamic column, direction, or table name against a fixed allow-list — never interpolate them to "help" the optimizer.
Testing
- Activation and decision behavior are verified in
eval/scenarios/performance/query-optimization.yaml.
Additional resources
- references/anti-patterns.md
- references/core.md
- references/examples.md
- references/pitfalls.md
- references/recipes.md
- references/version-differences.md
Knowledge graph
Related: databases/mysql-indexing, performance/n-plus-one, performance/opcache
<!-- graph-fragment: graph/fragments/performance/query-optimization.yaml -->Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

