What are database indexes and how to create them
· Category: SQL & Databases
Short answer
An index is a data structure that speeds up row lookups at the cost of additional storage and slower writes. Create indexes with CREATE INDEX.
Steps
- Create a single-column index:
CREATE INDEX idx_last_name ON employees(last_name); - Create a composite index:
CREATE INDEX idx_name ON employees(last_name, first_name); - Create a unique index:
CREATE UNIQUE INDEX idx_email ON users(email); - Drop an index:
DROP INDEX idx_name; - Analyze query plans with
EXPLAINto verify index usage.
Tips
- Index columns frequently used in
WHERE,JOIN,ORDER BY, andGROUP BYclauses. - Avoid over-indexing; each index adds overhead to inserts, updates, and deletes.
Common issues
- Indexes on low-cardinality columns (like boolean flags) rarely help and can hurt performance.
- Functions on indexed columns in
WHEREprevent the optimizer from using the index.r