“EXPLAIN ANALYZE” - also runs the query to show actual costs. • Prepend to your query in psql (script/dbconsole) • Rails also has ActiveRecord::Relation#explain eg User.order(:created_at).limit(10).explain
relevant rows are clustered next to each other • Ideally, your index would cover every field you are filtering/sorting on • Practically, you want the index to limit the # of rows left to filter/sort to a reasonable amount (<100)
filtering on a redundant column, there may be another way to filter • Consider splitting into 2 queries (or subquery, CTE) Especially useful with DISTINCT • Denormalize, as a last resort