使用 date_trunc 创建 Postgresql 索引

Create Postgresql index with date_trunc

与此有关。我想创建一个 returns 与此查询输出相同的索引;

--takes 2005-10-12
select date_trunc('month',table_withdates.dateoftransfer::date)::Date
from table_withdates;
--returns 2005-10-01

下面将索引但 returns 添加到日期的时间戳,这不是我想要的。

create index on table_withdates  (date_trunc('month', dateoftransfer::timestamp));
--returns 2005-10-01 00:00:00

是否可以创建一个索引,其中 returns 格式的日期没有时间戳

Quote from the manual

The return value is of type timestamp or interval with all fields that are less significant than the selected one set to zero

因此您需要将 date_trunc 的结果转换为日期:

create index on table_withdates  (date_trunc('month', dateoftransfer)::date);

请注意,为了使索引可用于查询,您需要使用完全相同的表达式,例如:

where date_trunc('month', dateoftransfer)::date  = ...