mysql-indexing
Skill4 starsChanged 4 months agoMITView on GitHub
Design MySQL indexes that make queries fast — B-tree vs hash, composite and covering indexes, leftmost-prefix rules, and reading EXPLAIN to confirm an index is actually used. Use when the user needs a multi-column (composite) or covering index for a query that filters, joins, or sorts on several columns at once; the user wants to run EXPLAIN (or EXPLAIN ANALYZE) and interpret the plan to understand which index MySQL chose, or why it fell back to a full scan; the user has a slow SELECT, JOIN, or ORDER BY that scans a large table and wants to add or fix an index so the database reads far fewer rows. Keywords: mysql, indexing, index, performance, explain, composite-index, covering-index, query-optimization, sql, database.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- rafapeixer/db-skillstheir own version, first seen Nov 8, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- rafapeixer/db-skills★ 1same 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
- redisSkill
- transactionsSkill
- ci-github-actionsSkill
- deployment-strategiesSkill
- docker-phpSkill
- env-configSkill
- associationsSkill
- entities-mappingSkill
- orm-basicsSkill
- entity-apiSkill
- module-developmentSkill
- routing-controllersSkill
- formsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 3 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 68
Do not apply these rules verbatim to PostgreSQL, SQLite, or a NoSQL store — their optimizers, index types, and covering semantics differ.
- Distinctive: line 70
Do not reach for new indexes when the table holds only a few hundred rows, or when the workload is overwhelmingly writes with rare reads.
- Very specific: line 84
Run EXPLAIN (or EXPLAIN ANALYZE on MySQL 8) on the slow query and note the type, key, and rows columns to see whether a full scan is …
- Distinctive: line 94
When a hot query selects only a few columns, add every selected and filtered column to one index so the query is answered entirely from the …
- Very specific: line 99
Write predicates so the indexed column stands alone on one side: prefer WHERE created_at >= '2026-01-01' over WHERE YEAR(created_at) = …
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “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/databases/mysql-indexing/ --><!-- schema: atomVersion=3 skillVersion=2 graphVersion=1 --><!-- compile: @php-skills/compiler v1.0.0 (deterministic build) -->MySQL Indexing
When to use
- The user needs a multi-column (composite) or covering index for a query that filters, joins, or sorts on several columns at once.
- The user wants to run EXPLAIN (or EXPLAIN ANALYZE) and interpret the plan to understand which index MySQL chose, or why it fell back to a full scan.
- The user has a slow SELECT, JOIN, or ORDER BY that scans a large table and wants to add or fix an index so the database reads far fewer rows.
When NOT to use
- Do not apply these rules verbatim to PostgreSQL, SQLite, or a NoSQL store — their optimizers, index types, and covering semantics differ.
- Do not reach for new indexes when the table holds only a few hundred rows, or when the workload is overwhelmingly writes with rare reads.
Core guidance
- Read the EXPLAIN type column before trusting an index — Run EXPLAIN and read the
typecolumn: aim forconst,eq_ref,ref, orrange. TreatALL(full scan) and a hugerowsestimate as a missing or unusable index, and confirmkeynames the index you intended. - Order composite columns by the leftmost-prefix rule — In a composite index, put equality-filtered columns first, then one range or
sort column last. A composite index on
(a, b, c)only helps queries that use a leftmost prefix —a, ora, b, ora, b, c— neverbalone.
Quick recipe
- Run
EXPLAIN(orEXPLAIN ANALYZEon MySQL 8) on the slow query and note thetype,key, androwscolumns to see whether a full scan is happening. (verify:typeisALLandrowsis large, confirming the query lacks a usable index.) - Build a composite index listing equality columns first, then the range or sort
column, and include selected columns to make it covering where cheap:
CREATE INDEX idx_orders_user_status_created ON orders (user_id, status, created_at). (verify: The index columns match the query's WHERE, JOIN, and ORDER BY usage in leftmost-prefix order.) - Re-run EXPLAIN to confirm
typeimproved toref/rangeandkeynames the new index, then time the query to verify a real latency win before shipping. (verify: EXPLAIN reports the new index inkey,rowsdropped sharply, and wall-clock time fell.)
Best practices
- When a hot query selects only a few columns, add every selected and filtered column to one index so the query is answered entirely from the index
- For long VARCHAR/TEXT columns, index a leading prefix (
INDEX (url(191))) instead of the whole value, choosing a length that keeps selectivity high while staying inside the index key-length limit - Write predicates so the indexed column stands alone on one side: prefer
WHERE created_at >= '2026-01-01'overWHERE YEAR(created_at) = 2026, and avoid wrapping the column in a function or a leading-wildcardLIKE '%foo' - Index columns whose values are highly selective (many distinct values, like
emailoruser_id)
Anti-patterns
| Anti-pattern | Why it fails | Do instead |
| Hard-coding FORCE INDEX to paper over a bad plan | The optimizer usually chooses well once statistics are fresh; a forced hint hides the real cause and breaks later. | Refresh statistics with ANALYZE TABLE, fix the index design or the predicate,<br>and reserve FORCE INDEX for a proven, documented optimizer mis-estimate. |
| Adding an index to every column | Over-indexing trades write throughput and disk for indexes the query planner never chooses. | Index only columns that appear in real WHERE, JOIN, and ORDER BY clauses, and<br>prefer composite indexes that serve several queries over many single-column ones. |
| SELECT * defeats covering indexes | A covering index only helps when the selected columns all live in the index; * guarantees they do not. | Select the explicit column list the code uses so a covering index can answer<br>the query, and let EXPLAIN confirm Using index. |
See references/anti-patterns.md.
Common mistakes
- Wrapping the indexed column in a function kills the index — A predicate like
WHERE DATE(created_at) = '2026-07-02'orWHERE LOWER(email) = ?makes the query non-sargable, so MySQL scans every row even thoughcreated_atoremailis indexed. Fix: Rewrite as a sargable range (created_at >= '2026-07-02' AND created_at < '2026-07-03'), store a normalized column, or add a functional/generated-column index on the expression. - Type mismatch causes a silent implicit cast and full scan — Comparing an indexed numeric column to a quoted string (
WHERE user_id = '42') or a VARCHAR column to a number forces an implicit type conversion that disables the index. Fix: Bind parameters with the correct PHP type so the driver sends a matching SQL type, and align column types across joined tables (both INT, or both VARCHAR with the same collation). - Redundant and duplicate indexes slow writes — Keeping an index on
(a)alongside(a, b)is redundant — the composite already coversa— and every duplicate index adds write overhead and storage with no read benefit. Fix: Drop the redundant single-column index, audit with a tool such as pt-duplicate-key-checker, and keep only indexes that a real query plan uses. - Composite index in the wrong column order is dead weight — An index on
(status, created_at)does nothing forWHERE created_at > ?with nostatusfilter, because the query does not use the leftmost prefix. Fix: Order composite columns by usage — equality predicates first, then the range or sort column — and add a separate index for queries that filter only on the trailing column.
Version notes
- EXPLAIN ANALYZE and invisible indexes arrived in MySQL 8 (PHP >=7.4) — MySQL 8.0 adds
EXPLAIN ANALYZE(real timed execution), descending indexes, functional indexes, and invisible indexes for safe rollout; MySQL 5.7 has only the estimate-basedEXPLAIN.
Security
- Index-driven queries still need prepared statements — Never interpolate user input into WHERE clauses while tuning indexes — bind the filter value as a parameter. Column and index names cannot be bound, so validate any dynamic ORDER BY column against a fixed allow-list.
Testing
- Activation and decision behavior are verified in
eval/scenarios/databases/mysql-indexing.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/connection-pooling, databases/transactions, security/sql-injection-prevention
<!-- graph-fragment: graph/fragments/databases/mysql-indexing.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.

