首页 > 解决方案 > PostgreSQL 中的索引

问题描述

我有一个问题要问,以帮助我更好地理解索引。我们看到这有什么不同吗:

1
create index insertion_test_timestamp1_idx
on insertion_test (timestamp1);

create index insertion_test2_timestamp1_idx
on insertion_test (id13);

和这个:

2
create index insertion_test_timestamp1_idx
on insertion_test (timestamp1,id13);

我使用的一些查询如下所示:

select * from timestampdb where timestamp1 >='2020-01-01 00:05:00' and timestamp1<='2020-01-02 00:05:00' and id13>'5',
select date_trunc('hour',timestamp1) as hour,avg(id13) from timestampdb where timestamp1 >='2020-01-01 00:05:00' and timestamp1<='2020-01-02 00:05:00' group by hour order by hour ,
select date_trunc('hour',timestamp1) as hour,max(id13) from timestampdb where timestamp1<='2020-01-01 00:05:00' group by hour order by hour desc limit 5,
select date_trunc('hour',timestamp1) as hour,max(id13) from timestamppsql where timestamp1 >='2020-01-01 00:05:00' and timestamp1<='2020-01-01 01:05:00' group by hour order by hour asc

我的版本是这样的:psql (PostgreSQL) 12.6 (Ubuntu 12.6-1.pgdg20.04+1)

标签: sqlpostgresqlindexingpostgresql-performance

解决方案


在你的情况下:

带有 where timestamp1 = 'sometimestamp' 的查询使用 op 1 带有 where id13 = someid13 的查询使用 op 1

带有 where timestamp1 = 'sometimestamp' 和 id13 = someid13 的查询,可以使用 op 2

带有 where id13 = someid13 和 timestamp1 = 'sometimestamp' 的查询,可以使用 op 1 或 op 2

为什么?因为一个索引选择涉及很多东西,基数、大小、统计、后选择操作等。

请记住,op 2 涵盖了 op 1 的第一个。


推荐阅读