Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain COUNT query with ActiveRecord

I want to do something like the following:

Post.count.explain # doesn't work

This fails because EXPLAIN is a method on Relation and Post.count isn't a relation. It's just a regular integer that is the result of the query. So how could a count query be EXPLAINed?

like image 410
mahemoff Avatar asked Sep 29 '15 02:09

mahemoff


2 Answers

Here's a form that generates the exact same SQL query, but returns a Relation to call explain on:

Post.select('count(*)').explain 

Both generate the SQL

 SELECT COUNT(*) FROM `posts`

...so the query plan should be the same.

like image 179
Mori Avatar answered Nov 06 '22 11:11

Mori


From ActiveRecord::Relation#explain, we can make that method accept a block.

module ExplainBlock
  def explain_block(&block)
    exec_explain(collecting_queries_for_explain { instance_exec(&block) })
  end
end

ActiveRecord::Relation.include(ExplainBlock)

Then Post.all.explain_block { count } .

like image 28
ypresto Avatar answered Nov 06 '22 10:11

ypresto