0

I have the following query:

select count(*), date_trunc('day', updated_at) from test group by date_trunc('day', updated_at);

and the when explaining I have the following:

GroupAggregate  (cost=213481.83..223749.85 rows=245009 width=8)
  ->  Sort  (cost=213481.83..215883.63 rows=960720 width=8)
      Sort Key: (date_trunc('day'::text, updated_at))
  ->  Index Only Scan using updatedat on test  (cost=0.00..91745.26 rows=960720 width=8)

As you can see it has a high cost, and the query time is 6231.58 ms.

Is there a way to improve this? What should be the best index to create for this kind of count/group/date_trunc mix.

2
  • 2 questions: What happens if you execute the query several times? Can you try with an index on date_trunc('day', updated_at') (postgresql allows to create index on expressions, not only on columns)? postgresql.org/docs/current/sql-createindex.html
    – FXD
    Jan 30, 2019 at 22:52
  • Please edit your question and add the execution plan generated using explain (analyze, buffers) ... (not just a simple explain).
    – user330315
    Jan 31, 2019 at 7:44

1 Answer 1

1

If there are really 250000 different days in your table, you probably cannot do much better than this. Increasing work_mem will speed up the sort though.

If, however, the number of different days is significantly lower, the problem is that PostgreSQL has no way to estimate the distribution of date_trunc's results unless you create an index:

CREATE INDEX ON test (date_trunc('day', updated_at));

If updated_at is a timestamp without time zone, that will work fine. For a timestamp with time zone, you'll have to specify a time zone, because otherwise the result will depend on the session time zone, which makes it unusable for an index:

CREATE INDEX ON test (date_trunc('day', updated_at AT TIME ZONE 'UTC'));

Then ANALYZE the table, increase work_mem and see if you can get a hash aggregate instead of a sort.

Of course, if you have to use AT TIME ZONEin the index definition, you'd also have to use it in the query...

1
  • I learnt a lot from that reply. You can read about group by for "resampling" like this in many places but the fact Postgres won't "see through" the date_trunc and realize that it preserves the order of the underlying timestamps and hence can't make use of an index on them (would you agree with that assessment?) is rarely mentioned. Another thing that came to mind was to use avg as a window function over a ranged window in a subquery from which we then filter out any values not at midnight (assuming there's always a value at midnight, i.e. fixed times). May 4, 2022 at 15:36

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.