How to Group by Time in PostgreSQL

When you want to group by minute, hour, day, week, etc., it's tempting to just group by your timestamp column, however, then you'll get one group per second, which is likely not what you want. Instead, you need to "truncate" your timestamp to the granularity you want, like minute, hour, day, week, etc. The PostgreSQL function you need here is date_trunc.

  date_trunc('minute', created_at), -- or hour, day, week, month, year
from users
group by 1

If you don't have new users every minute, you're going to have gaps in your data. To have one row per minute, even when there's no data, you'll want to use generate_series.

database icon
Better SQL for the people
Get more done with PopSQL and PostgreSQL