If I want to group a column of timestamps, say registered_at
by the day on which they occurred, I can use either date_trunc('day', registered_at)
or registered_at::date
. The first removes the hours and smaller units from the timestamp, but still returns a timestamp, while the latter returns the timestamp cast to a date. Now, I'm wondering if any of the two has a better performance than the other.
When I look at the query plans, the theoretical costs are exactly the same, and there can be a lot of noise in the actual execution times.
-- SELECT date_trunc('day', registered_at)
Seq Scan on customers (cost=0.00..5406.45 rows=23987 width=8) (actual time=0.023..46.811 rows=24436 loops=1)
Filter: (created_at > '2019-06-01 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 113958
Planning time: 0.107 ms
Execution time: 48.158 ms
-- SELECT registered_at::date
Seq Scan on customers (cost=0.00..5406.45 rows=23987 width=4) (actual time=0.017..34.353 rows=24436 loops=1)
Filter: (created_at > '2019-06-01 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 113958
Planning time: 0.121 ms
Execution time: 35.548 ms
Does anyone have an idea which method would be faster, either when truncating or when subsequently using group by
?