Last Updated: February 25, 2016
·
1.306K
· weyus

Getting PostgreSQL query explain plans in Rails pre-3.2.x

Start up a Rails console:

Use "to_sql" to get your query in plain SQL, e.g.

stmt = Widget.active.to_sql 

will yield something like

SELECT * FROM \"widgets\" WHERE (active = 't')

assuming that active is a scope like

scope :active, where(active: true)

Then run the following:

Widget.connection.execute("EXPLAIN #{stmt}").each_entry {|x| puts x['QUERY PLAN']}

and you will get the standard PostgreSQL query explain plan output.