简体   繁体   English

PostgreSQL:为什么这个简单的查询不使用索引?

[英]PostgreSQL: Why does this simple query not use the index?

I have a table t with a column c, which is an int and has a btree index on it. 我有一个带有列c的表t,它是一个int并且在其上有一个btree索引。

Why does the following query not utilize this index? 为什么以下查询不使用此索引?

explain select c from t group by c;

The result I get is: 我得到的结果是:

HashAggregate  (cost=1005817.55..1005817.71 rows=16 width=4)
  ->  Seq Scan on t  (cost=0.00..946059.84 rows=23903084 width=4)

My understanding of indexes is limited, but I thought such queries were the purpose of indexes. 我对索引的理解是有限的,但我认为这些查询是索引的目的。

This query can be performed using an optimization called a loose index scan . 可以使用称为松散索引扫描的优化来执行此查询。 However PostgreSQL doesn't yet implement this optimization, so it uses a table scan instead. 但PostgreSQL尚未实现此优化,因此它使用表扫描。

Of the major databases, as far as I know only MySQL has implemented loose index scan (perhaps Oracle too?). 在主要的数据库中,据我所知,只有MySQL实现了松散的索引扫描 (也许也是Oracle?)。 PostgreSQL hasn't implemented this feature. PostgreSQL 尚未实现此功能。

The query certainly can use an index. 查询当然可以使用索引。 The reason that it doesn't in your particular case depends on the particular size and distribution of the data. 它不在您的特定情况下的原因取决于数据的特定大小和分布。 You can use SET enable_seqscan TO off to investigate. 您可以使用SET enable_seqscan TO off来调查。

Because it requires scanning the entire table, so doing that via the index is of no benefit. 因为它需要扫描整个表,所以通过索引这样做是没有好处的。 ("Covering indices" aren't useful as a performance technique in PostgreSQL due to its MVCC implementation). (由于其MVCC实现,“覆盖索引”在PostgreSQL中作为一种性能技术无用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM