There is nothing wrong with using date_trunc
under the right circumstances.
The main issue is where b-tree indexes are involved. If you have an index on some_timestamp
and you search for date_trunc('day', some_timestamp) = DATE '2012-01-01'
, PostgreSQL can't use the index.
(It could theoretically rewrite the date_trunc
expression into an indexable range predicate, but it doesn't).
If you instead write:
some_timestamp >= DATE '2012-01-01' AND some_timestamp < DATE '2012-01-02'
then it's b-tree indexable. (Note that I intentionally did not use BETWEEN
because it's both-inclusive).
It's sometimes useful to create an expression index, e.g.
create index blahindex on blahtable (date_trunc('day', some_timestamp));
but as each extra index has a maintenance cost it's better to just write your predicates to be easily usable with normal column indexes where possible.