PostgreSQL: Index the day part of a timestamp

大憨熊 提交于 2019-12-18 04:43:05

问题


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 "::"

回答1:


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) );



回答2:


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.



来源:https://stackoverflow.com/questions/34293233/postgresql-index-the-day-part-of-a-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!