Read more

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

Emanuel
December 19, 2017Software engineer at makandra GmbH

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
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

Posted by Emanuel to makandra dev (2017-12-19 09:34)