Rails and Postgres: How to test if your index is used as expected

This is a small example on how you can check if your Postgres index can be used by a specific query in you Rails application. For more complex execution plans it might still be a good idea to use the same path of proof.

1. Identify the query your application produces

query = User.order(:last_name, :created_at).to_sql
puts query
# => SELECT "users".* FROM "users" ORDER BY "users"."last_name" ASC, "users"."created_at" ASC

2. Add an index in your migration and migrate

add_index :users, [:last_name, :created_at]

3. Test the index in your database

ActiveRecord::Base.connection.execute('SET enable_seqscan = OFF') # Try to force index only scan even seq scan is faster

explain = "EXPLAIN ANALYSE #{query}"
ActiveRecord::Base.connection.execute(explain).each {|result| puts result}
# => {"QUERY PLAN"=>"Index Scan using index_users_on_last_name_and_created_at on users  (cost=0.28..140.10 rows=1164 width=187) (actual time=0.045..0.499 rows=1164 loops=1)"}
# => {"QUERY PLAN"=>"Planning time: 0.096 ms"}
# => {"QUERY PLAN"=>"Execution time: 0.592 ms"}

ActiveRecord::Base.connection.execute('SET enable_seqscan = ON') # Don't forget to reset query planner's settings

This proves that the query can use the index on last_name and created_at if it is the cheapest execution plan.

Emanuel Over 6 years ago