Skip to main content

ActiveRecord explain: Read the Query Plan

Call explain on any Relation to see the PostgreSQL plan. Pass :analyze to run the query and get real timings. In irb, puts the result to print the plan. The Relation::ExplainProxy object only inspects as an object.

Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.

The conversion

SQL

EXPLAIN ANALYZE
SELECT * FROM posts WHERE published = true

ActiveRecord

puts Post.where(published: true).explain(:analyze)

SQL that Rails 8.1.1 generates

EXPLAIN (ANALYZE) SELECT "posts".* FROM "posts" WHERE "posts"."published" = $1 [["published", true]]
Seq Scan on posts (cost=0.00..18.70 rows=435 width=65) (actual time=0.001..0.002 rows=6 loops=1)
  Filter: published
  Rows Removed by Filter: 3
Planning Time: 0.008 ms
Execution Time: 0.005 ms

A cleaner alternative

puts Post.where(published: true).explain(:analyze, :buffers)

Rails 7.1 and later accept options such as :analyze, :buffers and :verbose. Rails turns them into EXPLAIN (ANALYZE, BUFFERS).

What goes wrong

ANALYZE runs the query

explain(:analyze) executes the statement. On a SELECT that is safe but real. Do not point it at a production query that takes minutes without a statement timeout.

Seq Scan on a tiny table is correct

Our test table has 9 rows, so PostgreSQL chose a Seq Scan. That does not mean you need an index. Test on data the size of production.

Read these fields first

Look at the node type (Seq Scan, Index Scan), rows estimated vs actual, Rows Removed by Filter, and Execution Time. A big gap between estimated and actual rows points to stale statistics.

The proxy needs puts

explain returns an ExplainProxy. Use puts, or call to_s, to see the plan text.

Convert your own EXPLAIN query

Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.

Questions

How do I run EXPLAIN ANALYZE in Rails?

Call explain(:analyze) on a Relation, for example puts Post.where(published: true).explain(:analyze).

Does ActiveRecord explain run the query?

Plain explain does not run it. explain(:analyze) does run it, and reports actual time and rows.

How do I see buffer usage?

Use explain(:analyze, :buffers). Rails 7.1 and later pass the options to PostgreSQL.