1mangesh1/dev-skills-collection/database-indexing
Claude Code and agent skill by 1mangesh1/dev-skills-collection
- community
Checking that the SKILL.md file is still in the repository.
Database indexing internals, index type selection, query plan analysis, and write-overhead tradeoffs across PostgreSQL, MySQL, and MongoDB. Use when user asks to "optimize queries", "create indexes", "fix slow queries", "read EXPLAIN output", "reduce query time", "index strategy", "database performance", "composite index", "covering index", "partial index", "index bloat", "unused indexes", or needs help diagnosing and resolving database performance problems.
Install
npx vskill@latest install 1mangesh1/dev-skills-collection/database-indexingSKILL.md
Database Indexing
What an Index Does
An index is a separate data structure that maps column values to the physical locations of rows. Without an index, the database must perform a sequential scan (full table scan), reading every row to find matches. With an index, the database navigates a much smaller structure to locate rows directly.
B-tree Structure
The default index in PostgreSQL and MySQL (InnoDB) is a B-tree -- a balanced, sorted tree where the root node contains boundary keys and pointers to child nodes, internal nodes narrow the search range at each level, and leaf nodes hold the indexed values paired with pointers to the actual table rows. Leaf nodes are linked in order, so range scans walk the leaf chain without returning to upper levels.
A lookup traverses from root to leaf in O(log n) steps. For a table with 10 million rows, a B-tree typically requires 3-4 page reads to locate a single value.
How a Lookup Works
- The query planner determines that an index is useful for the query.
- The database reads the root page and follows pointers through internal pages based on comparison with search keys.
- It reaches a leaf page containing the target value and a pointer to the heap (table row).
- It fetches the row from the heap (unless the index covers all required columns).
When to Add Indexes
Add indexes on columns that appear in:
- WHERE clauses with equality or range conditions on selective columns.
- JOIN conditions -- foreign key columns used in joins almost always need indexes.
- ORDER BY / GROUP BY -- an index matching the sort order avoids a separate sort step.
- Unique constraints -- these implicitly create indexes.
Index columns with high selectivity (many distinct values relative to row count). If a query runs frequently and scans a large portion of the table, it is a candidate. Measure before and after -- do not guess.
When NOT to Index
- Small tables (under a few thousand rows). A sequential scan is often faster than the overhead of index lookups because the entire table fits in a few pages.
- High-write, low-read tables (logging tables, event streams). Every INSERT, UPDATE, and DELETE must also update every index on the table.
- Low-cardinality columns (boolean flags, status columns with 3-5 values). The index does not narrow the search enough to justify the overhead. Exception: partial indexes on a rare value can still help.
- Columns rarely used in queries. An index that is never used wastes storage and slows writes.
Index Types
B-tree
Default in PostgreSQL and MySQL. Supports equality, range (<, >, BETWEEN), IS NULL, LIKE 'prefix%' (but not LIKE '%suffix'), and ORDER BY. Use B-tree unless you have a specific reason to choose something else.
Hash
Supports only equality comparisons (=). In PostgreSQL, hash indexes are WAL-logged since version 10 and are safe to use, but they rarely outperform B-tree. In MySQL (InnoDB), hash indexes exist only in the adaptive hash index (internal, automatic). Use hash indexes only when you are certain you will never need range queries on that column.
GIN (Generalized Inverted Index) -- PostgreSQL
Designed for values that contain multiple elements: arrays, JSONB, full-text search (tsvector), and trigram similarity. GIN indexes map each element to the set of rows containing it. They are larger and slower to update than B-tree but excel at containment queries (@>, &&, @@).
GiST (Generalized Search Tree) -- PostgreSQL
Supports geometric data, range types, full-text search, and nearest-neighbor queries. GiST is lossy for some data types (it may return false positives that are rechecked). Use for spatial queries (<-> distance operator) and range overlap (&&).
BRIN (Block Range Index) -- PostgreSQL
Stores min/max summaries for each block range in the table. Extremely small index size. Effective only when physical row order correlates with column values -- common for timestamp columns on append-only tables. Useless if values are randomly distributed across pages.
Composite Indexes
A composite (multi-column) index indexes two or more columns together.
Column Order and the Leftmost Prefix Rule
A composite index on (a, b, c) can satisfy queries that filter on:
aaandba,b, andc
It cannot efficiently satisfy queries that filter only on b, only on c, or on b and c without a. The leftmost prefix must be present.
Choosing Column Order
- Place equality columns first, range columns last. A query
WHERE status = 'active' AND created_at > '2025-01-01'benefits from an index on(status, created_at), not(created_at, status). - If the same columns appear in different query patterns with different leading columns, you may need separate indexes.
Partial Indexes
A partial index includes only rows that satisfy a condition. This reduces index size and maintenance cost.
This index is used only when the query includes WHERE active = true (or a condition the planner can prove implies it). Useful for:
- Indexing a small subset of a large table (e.g., unprocessed jobs, recent records).
- Replacing a full index on a low-cardinality column with a filtered index on the rare value.
Partial indexes are supported in PostgreSQL. MySQL does not support them.
Covering Indexes (INCLUDE Columns)
A covering index contains all columns needed by a query, so the database never visits the heap (table) at all. This is called an index-only scan.
In PostgreSQL 11+, use INCLUDE to add non-searchable columns to the index:
The INCLUDE columns are stored in leaf pages but are not part of the tree structure, so they do not affect search or ordering. The query SELECT total, status FROM orders WHERE customer_id = 42 can be answered entirely from the index.
In MySQL (InnoDB), the primary key is appended to every secondary index automatically, which makes secondary indexes partially covering by default.
Expression Indexes
Index the result of a function or expression rather than a raw column value.
This index is used only when the query matches the exact expression: WHERE lower(email) = 'user@example.com'. It will not be used for WHERE email = 'user@example.com'.
Common uses: case-insensitive lookups, extracting JSONB fields, date truncation (CREATE INDEX idx_year ON events ((extract(year FROM event_date)))).
Reading EXPLAIN and EXPLAIN ANALYZE
Basic Usage
EXPLAIN shows the planned execution without running the query. EXPLAIN ANALYZE runs the query and shows actual timings and row counts. Use EXPLAIN ANALYZE in development -- never on production with destructive statements (it executes the query).
Key Scan Types
- Seq Scan -- reads every row in the table. Expected on small tables or non-selective filters.
- Index Scan -- traverses the index, then fetches rows from the heap. Standard index usage.
- Index Only Scan -- reads only the index, never visits the heap. Requires a covering index and a recently vacuumed table (visibility map must be up to date).
- Bitmap Index Scan -- builds a bitmap of matching pages from the index, then fetches pages in physical order. Used when too many rows match for a plain index scan but too few for a sequential scan.
What to Look For
- Large gaps between estimated rows and actual rows indicate stale statistics. Run
ANALYZE. Seq Scanon a large table with a selectiveWHEREclause suggests a missing index.Sortnodes with high cost may be eliminated by an index matching theORDER BY.- Nested loop joins on unindexed columns produce O(n*m) behavior.
Index Maintenance
Bloat
UPDATE and DELETE operations in PostgreSQL do not remove index entries immediately. Dead tuples accumulate, causing index bloat. Autovacuum cleans up dead tuples, but under heavy write loads it may fall behind.
Monitor bloat:
REINDEX
Rebuilds an index from scratch, removing bloat. Locks the table for writes in standard mode. Use REINDEX CONCURRENTLY (PostgreSQL 12+) for online rebuilds.
Finding Unused Indexes
Indexes with zero scans since the last statistics reset are candidates for removal. Verify no rare but critical queries depend on them before dropping.
MySQL vs PostgreSQL Index Differences
| Feature | PostgreSQL | MySQL (InnoDB) | |
|---|---|---|---|
| Clustered index | Optional (via CLUSTER) | Always on primary key | |
| Secondary indexes | Point to heap tuple (ctid) | Store the primary key value | |
| Partial indexes | Supported | Not supported | |
| Expression indexes | Supported | Supported (8.0.13+, functional indexes) | |
| INCLUDE columns | Supported (11+) | Not supported | |
| GIN, GiST, BRIN | Supported | Not available | |
| Hash indexes | WAL-logged, explicit | Adaptive hash index (internal only) | |
| Online DDL | CREATE INDEX CONCURRENTLY | ALTER TABLE ... ALGORITHM=INPLACE | |
| Covering index syntax | INCLUDE (cols) | All InnoDB indexes include PK |
In MySQL InnoDB, the table is a clustered B-tree ordered by primary key. Secondary index lookups require a second traversal (secondary index to PK, then PK to row), making primary key choice critical -- use a compact, auto-incrementing integer.
MongoDB Indexes
Single Field and Compound Indexes
Compound indexes follow the same leftmost prefix rule as relational databases. The direction (1 ascending, -1 descending) matters for sort operations.
Text Indexes
One text index per collection. Supports language-specific stemming and stop words.
TTL Indexes
Automatically delete documents after a specified time. Only works on Date fields, single-field only:
Sparse and Partial Filter Indexes
Sparse indexes include only documents where the field exists, reducing index size. Prefer partialFilterExpression (MongoDB 3.2+) for more control:
Common Anti-patterns
Indexing every column. Each index consumes storage and slows every write. A table with 15 indexes on 20 columns is almost certainly over-indexed.
Redundant indexes. An index on (a, b) makes a separate index on (a) redundant, because the composite index satisfies single-column lookups on a. Check for these and remove them.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/database-indexing/SKILL.md
Popularity
- Repository stars
- 2
- 7-day trend score
- 5
Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 23 Mar 2026, 8 months ago.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/1mangesh1/dev-skills-collection/database-indexing)