Retrieving minimum value becomes every slow in Postgres

65 views Asked by At

I found a strange problem on Postgresql which retrieving minimum value from a small table with 11 row spent almost 200ms.

Initializing a data, turning off autovacuum and starting it.Then executing below sqls.

create table test1(a int);
insert into test1 select generate_series(1, 10000000);
vacuum analyze test1;
create index on test1(a);
delete from test1 where a < 9999990;`

Executing sql select min(a) from test1; select max(a) from test2;

enter image description here

Above image shows spending 197.443 ms to obtain minimum value but getting maximum value only spent 0.084 ms. They both used index only scan. Why them have a such big difference between getting minimum and maximum value. I know vacuuming this table can resolve this performance problem, but I don't know the reason. In my opinion, index only scan is the fastest retrieve method. It's unconceivable. Expecting someone can explain it. Thank you first!

1

There are 1 answers

1
phani kumar Piratla On

after delete it is left with 11 rows only. min and max timing you may be taking immediately after delete ? after few executions it is coming same time. but if you have huge data and execute min number of times then you will see difference in time between select min(a) from test11; select a from test11 order by a limit 1; Second is much faster.