Database indexes for query optimization

8950
0

Proper indexing is the difference between millisecond and multi-second query response times. I add indexes to foreign keys automatically since Rails doesn't do this by default, and I create composite indexes for common query patterns that filter on multiple columns. The EXPLAIN output guides index decisions—when I see sequential scans on large tables, that's a signal to add an index. Partial indexes are particularly useful for queries that filter on a specific condition frequently, like WHERE deleted_at IS NULL. I also use index: { unique: true } in migrations to enforce data integrity constraints at the database level. Monitoring slow query logs in production reveals which indexes deliver the most value.