我在 PostgreSQL 中有下表:
CREATE TABLE index_test
(
id int PRIMARY KEY NOT NULL,
text varchar(2048) NOT NULL,
last_modified timestamp NOT NULL,
value int,
item_type varchar(2046)
);
CREATE INDEX idx_index_type ON index_test ( item_type );
CREATE INDEX idx_index_value ON index_test ( value )
我做了以下选择:
explain select * from index_test r where r.item_type='B';
explain select r.value from index_test r where r.value=56;
执行计划的解释是这样的:
Seq Scan on index_test r (cost=0.00..1.04 rows=1 width=1576) Filter: ((item_type)::text = 'B'::text)'
据我了解,这是全表扫描。问题是:为什么我的索引没有被使用?
可能是因为我的表行数太少?我只有 20 个。能否请您提供一个 SQL 语句来轻松地用随机数据填充我的表以检查索引问题?
我找到了这篇文章:http://it.toolbox.com/blogs/db2luw/how-to-easily-populate-a-table-with-random-data-7888 ,但这对我不起作用。语句的效率并不重要,重要的是简单性。
最佳答案
Maybe, the reason is that I have too few rows in my table?
是的。对于表中总共 20 行,seq 扫描总是比索引扫描快。无论如何,这些行很可能位于单个数据库 block 中,因此 seq 扫描只需要一个 I/O 操作。
如果你使用
explain (analyze true, verbose true, buffers true) select ....
您可以看到有关实际情况的更多详细信息。
顺便说一句:您不应该使用 text
作为列名,因为它也是 Postgres 中的数据类型(因此是保留字)。
关于sql - 为什么 PostgreSQL 不在小表上使用我的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30888571/