PostgreSQL: Index the day part of a timestamp

2019-01-25 11:52发布

Consider the following table:

       Column       |           Type           |
--------------------+--------------------------+
 id                 | bigint                   |
 creation_time      | timestamp with time zone |
...

Queries like the following (let alone more complicated JOINs) takes quite a while, because they needs to calculate creation_time::DATE for each item:

SELECT creation_time::DATE, COUNT(*) FROM items GROUP BY 1;

How do I create an index on the day part of the timestamp - creation_time::DATE?

I have tried:

  • CREATE INDEX items_day_of_creation_idx ON items (creation_time)::date;
  • CREATE INDEX items_day_of_creation_idx ON items (creation_time::date);

But both failed with:

ERROR:  syntax error at or near "::"

2条回答
We Are One
2楼-- · 2019-01-25 12:04

When you create an index on an expression that expression must be put between parentheses (in addition to the parentheses that surround the column/expression list:

CREATE INDEX items_day_of_creation_idx ON items ( (creation_time::date) );
查看更多
ら.Afraid
3楼-- · 2019-01-25 12:04

This worked, but I noticed that the index using an expression to cast a timestamp to a date used more disk space (~15%-20%) than an index on the timestamp.

I hoped for a disk space reduction in building an index on a 4 byte date over a 8 byte timestamp, but it seems that's not the case because 8 bytes seems to be the lowest common denominator for an element in the index. So, the disk use was worse, and the query performance was about the same, so I abandoned this approach.

查看更多
登录 后发表回答