Search code examples
postgresqlexplain

Understanding simple PostgreSQL EXPLAIN


I can't understand EXPLAIN of quite simple query:

select * from store  order by id desc limit 1;
QUERY PLAN Limit  (cost=0.00..0.03 rows=1 width=31)
  ->  Index Scan Backward using store_pkey on store  (cost=0.00..8593.28 rows=250000 width=31)

Why does top level node (limit) have cost lower than nested(index scan) has? As I read from documentation it should be cumulative cost, i.e. 8593.28 + 0.03


Solution

  • The docs (emphasis added) say;

    Actually two numbers are shown: the start-up cost before the first row can be returned, and the total cost to return all the rows. For most queries the total cost is what matters, but in contexts such as a subquery in EXISTS, the planner will choose the smallest start-up cost instead of the smallest total cost (since the executor will stop after getting one row, anyway).

    In other words, 8593.28 would be the cost to return all the rows, but due to the limit you're only returning one so the actual cost is much lower (more or less equal to the startup cost)