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

后端 未结 2 1727
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 03:22

I have the following table in PostgreSQL:

CREATE TABLE index_test
(
    id int PRIMARY KEY NOT NULL,
    text varchar(2048) NOT NULL,
    last_modified times         


        
相关标签:
2条回答
  • 2020-12-04 03:34

    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.

    0 讨论(0)
  • 2020-12-04 03:52

    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).

    0 讨论(0)
提交回复
热议问题