Search code examples
ruby-on-rails-3postgresqlexplain

Understanding Rails / PG Explain


I know it's kind of an awkward question.. but I don't understand what EXPLAIN explains..

My query is User.last, it took more than 0.5 second This is probably the simplest of queries, but it seems explain has trouble explaining it..

I don't understand anything that comes after QUERY PLAN Whats width? what is cost? How does it explain where the query took more time?

[40] pry(main)> User.last
  User Load (671.0ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
  EXPLAIN (39.0ms)  EXPLAIN SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
EXPLAIN for: SELECT  "users".* FROM "users"  ORDER BY "users"."id" DESC LIMIT 1
                             QUERY PLAN
--------------------------------------------------------------------
 Limit  (cost=1.08..1.08 rows=1 width=2861)
   ->  Sort  (cost=1.08..1.09 rows=5 width=2861)
         Sort Key: id
         ->  Seq Scan on users  (cost=0.00..1.05 rows=5 width=2861)
(4 rows)

Solution

  • Query Plan displays performance cost for each part of the query.

    For example:

    • cost=0.00 - Estimated start-up cost (Time expended before output scan can start, e.g., time to do the sorting in a sort node.)
    • ..1.05 - Estimated total cost (If all rows were to be retrieved, which they may not be: for example, a query with a LIMIT clause will stop short of paying the total cost of the Limit plan node's input node.)
    • rows=5 - Estimated number of rows output by this plan node (Again, only if executed to completion.)
    • width=2861 - Estimated average width (in bytes) of rows output by this plan node

    From here.

    For more information check this and that links.