Optimize Queries

Improve query performance with indexing, eager loading, and query optimization techniques.

Prerequisites

  • Working CQL application

  • Understanding of your data access patterns

Add Database Indexes

Indexes dramatically speed up queries on frequently searched columns.

Single Column Index

class AddIndexes < CQL::Migration(1)
  def up
    add_index :users, :email
    add_index :posts, :user_id
    add_index :posts, :published_at
  end

  def down
    remove_index :users, :email
    remove_index :posts, :user_id
    remove_index :posts, :published_at
  end
end

Composite Index

For queries filtering on multiple columns:

Unique Index

Enforce uniqueness and speed up lookups:

Use Select to Limit Columns

Only fetch columns you need:

Use Pluck for Single Values

When you only need specific columns without model objects:

Limit Result Sets

Always paginate or limit large queries:

Use Count Instead of Size

For counting records without loading them:

Batch Processing

Process large datasets in batches:

Use Exists Instead of Count

When checking for presence:

Optimize Ordering

Ensure ordered columns are indexed:

Analyze Slow Queries

Log queries to find bottlenecks:

Verify Optimization

Check query execution plans:

Look for:

  • Index scans (good) vs sequential scans (bad)

  • Low row estimates

  • Efficient join methods

See Also

Last updated

Was this helpful?