Why is PostgreSQL not using my indexes on a small table?

白昼怎懂夜的黑 提交于 2019-11-28 14:10:41

Maybe, the reason is that I have too few rows in my table?

Yes. For a total of 20 rows in a table a seq scan is always going to be faster than an index scan. Chances are that those rows are located in a single database block anyway, so the seq scan would only need a single I/O operation.

If you use

explain (analyze true, verbose true, buffers true) select ....

you can see a bit more details about what is really going on.

Btw: you shouldn't use text as a column name, as that is also a datatype in Postgres (and thus a reserved word).

The example you have found is for DB2, in pg you can use generate_series to do it. For example like this:

INSERT INTO index_test(data,last_modified,value,item_type) 
SELECT
    md5(random()::text),now(),floor(random()*100),md5(random()::text) 
    FROM generate_series(1,1000);
SELECT max(value) from index_test;

http://sqlfiddle.com/#!12/52641/3

The second query in above fiddle should use index only scan.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!