首页 > 解决方案 > 在 Postgres 中创建索引的理想顺序

问题描述

我有一个名为的表timestamppsql。我要在其上创建索引的列被称为timestamp1id13。我将测试一堆查询,但它们中的大多数看起来像这样:

 select date_trunc('day',timestamp1) as day,avg(id13) from timestamppsql where timestamp1 >='2010-01-01 00:05:00' and timestamp1<='2015-01-01 00:05:00' group by day order by day desc,

和这样的东西

select id13 from timestamppsql where timestamp1 >='2010-01-01 00:05:00' and timestamp1<='2011-01-01 00:05:00',  
select avg(id13)::numeric(10,2) from timestamppsql where timestamp1>='2015-01-01 00:05:00' and timestamp1<='2015-01-01 10:30:00'

我将创建一个索引:

create index project_index on timestamppsql(timestamp1,id13);

问题是索引的正确顺序是什么?timestamp1首先还是id13?我知道按顺序排列的第一个索引(从左到右)应该是我们使用较多的索引,重复值最少且列限制最多。您对此有何看法?

标签: sqlpostgresqlindexing

解决方案


WHERE子句是索引创建的主要子句。您希望索引首先支持过滤。因此,timestamp1对于这些查询,您需要在 id13` 之前。

请注意,通常 Postgres 即使在使用索引时也会访问数据页,因此在索引中使用id13可能并不重要。Postgres 在最近的版本中改进了优化,因此在没有修改的表中,可以使用覆盖索引。这就是说timestamp1作为索引中的第一列非常重要。 id13不那么重要。


推荐阅读