Implementing Database Indexes
1. Creating Single Field Index
@@index([email])
| Aspect | Detail |
|---|---|
| Type | B-tree default |
| Use | Equality + range queries |
2. Defining Composite Indexes
| Rule | Detail |
|---|---|
| Leftmost prefix | Index covers queries on leading fields |
| Order matters | Match query patterns |
| Example | @@index([tenantId, createdAt(sort: Desc)]) |
3. Using Unique Indexes
| Approach | Detail |
|---|---|
| Field-level | @unique |
| Composite | @@unique([...]) |
| Auto index | Both create unique B-tree |
4. Setting Custom Index Names
| Option | Detail |
|---|---|
map | DB-side index name |
| Convention | idx_table_columns |
5. Creating Partial Indexes
| DB | Approach |
|---|---|
| PG | Raw SQL: CREATE INDEX ... WHERE active = true |
| MySQL | Not directly supported |
6. Using Full-Text Indexes
| DB | Syntax |
|---|---|
| MySQL | @@fulltext([title, body]) |
| PG | Preview fullTextSearchPostgres; use tsvector in migrations |
7. Implementing Hash Indexes
@@index([token], type: Hash)
| Use | Detail |
|---|---|
| Equality only | No range queries |
| PG | Hash index supported (durable since PG10) |
8. Optimizing Query Performance
| Tip | Detail |
|---|---|
| Cover queries | Index all columns in where + orderBy |
| Avoid over-indexing | Slows writes |
| EXPLAIN | Inspect query plans |
9. Analyzing Index Usage
| DB Query | Use |
|---|---|
| PG | pg_stat_user_indexes |
| MySQL | sys.schema_unused_indexes |
| Tool | pganalyze, PMM, Performance Insights |
10. Managing Index Maintenance
| Action | When |
|---|---|
| REINDEX | After bulk updates (PG) |
| Analyze | Refresh planner stats |
| Drop unused | Reduce write amplification |