sql - 在 Postgres 中创建索引的理想顺序
问题描述
我有一个名为的表timestamppsql
。我要在其上创建索引的列被称为timestamp1
和id13
。我将测试一堆查询,但它们中的大多数看起来像这样:
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
?我知道按顺序排列的第一个索引(从左到右)应该是我们使用较多的索引,重复值最少且列限制最多。您对此有何看法?
解决方案
该WHERE
子句是索引创建的主要子句。您希望索引首先支持过滤。因此,timestamp1
对于这些查询,您需要在 id13` 之前。
请注意,通常 Postgres 即使在使用索引时也会访问数据页,因此在索引中使用id13
可能并不重要。Postgres 在最近的版本中改进了优化,因此在没有修改的表中,可以使用覆盖索引。这就是说timestamp1
作为索引中的第一列非常重要。 id13
不那么重要。
推荐阅读
- templates - 为什么我的树枝代码没有在我的视图文件中呈现模板?
- c++ - CMake 将 C++ 参数传递给 nvcc
- amazon-web-services - 再次运行查询时,AWS Athena 查询返回格式不正确的结果
- r - 有条件地更改最后一列的值
- objective-c - 在Objective-C中,当实现一个在后台任务完成后调用完成处理程序的方法时,如何确定线程安全?
- python - 在 Python 中编写条件语句的更简洁的方法
- copy-paste - 在 Python 中复制文件 - 读写 vs Shutil.copy
- kotlin - Kotlin 如何使用扩展单个基类的对象创建缓存
- flutter - 颤动中的盒子阴影没有出现
- mysql - 检查子查询结果是否存在,然后减去它