ruby 14 lines · 1 tab

Database indexes for query optimization

Alex Kumar Jan 2026
1 tab
class AddIndexesToPosts < ActiveRecord::Migration[6.1]
  def change
    add_index :posts, :author_id
    add_index :posts, :published_at
    add_index :posts, [:author_id, :published_at]
    add_index :posts, :created_at, order: { created_at: :desc }

    # Partial index for active published posts
    add_index :posts, :id, where: 'published_at IS NOT NULL AND deleted_at IS NULL', name: 'index_posts_published_active'

    # GIN index for array column tag searches
    add_index :posts, :tags, using: :gin
  end
end
1 file · ruby Explain with highlit

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.


Related snips

Share this code

Here's the card — post it anywhere.

Database indexes for query optimization — share card
Link copied