Search code examples
postgresqlb-tree

Why postgres "scan index(btree)" phase of plan returns all rows?


I have some misunderstanding with btree using Postgres 9.6.

I'm using SELECT max(total_amount) FROM bookings;

Total rows count 2111110, total_amount - numeric(10,2)

I have index on this column

CREATE INDEX ON bookings USING btree (total_amount);

When I'm using explain I see:

enter image description here

And as I know Btree is ordered tree, so to find min key value you should go left from root to end, maximum - right

So why postgres gets all rows but not one from scan index node?


Solution

  • No it doesn't get all the rows - if you look closely there is a Limit step right above the Index Only Scan Backwards - and that estimates only 1 row. So the index scan stops after the first row that was retrieved from the index.