Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

date - PostgreSQL: Index the day part of a timestamp

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 "::"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...