Implementing Database Indexes

1. Creating Single Field Index

@@index([email])
AspectDetail
TypeB-tree default
UseEquality + range queries

2. Defining Composite Indexes

RuleDetail
Leftmost prefixIndex covers queries on leading fields
Order mattersMatch query patterns
Example@@index([tenantId, createdAt(sort: Desc)])

3. Using Unique Indexes

ApproachDetail
Field-level@unique
Composite@@unique([...])
Auto indexBoth create unique B-tree

4. Setting Custom Index Names

OptionDetail
mapDB-side index name
Conventionidx_table_columns

5. Creating Partial Indexes

DBApproach
PGRaw SQL: CREATE INDEX ... WHERE active = true
MySQLNot directly supported

6. Using Full-Text Indexes

DBSyntax
MySQL@@fulltext([title, body])
PGPreview fullTextSearchPostgres; use tsvector in migrations

7. Implementing Hash Indexes

@@index([token], type: Hash)
UseDetail
Equality onlyNo range queries
PGHash index supported (durable since PG10)

8. Optimizing Query Performance

TipDetail
Cover queriesIndex all columns in where + orderBy
Avoid over-indexingSlows writes
EXPLAINInspect query plans

9. Analyzing Index Usage

DB QueryUse
PGpg_stat_user_indexes
MySQLsys.schema_unused_indexes
Toolpganalyze, PMM, Performance Insights

10. Managing Index Maintenance

ActionWhen
REINDEXAfter bulk updates (PG)
AnalyzeRefresh planner stats
Drop unusedReduce write amplification