Explain Codes LogoExplain Codes Logo

Grouping timestamps by day, not by time

sql
date-functions
performance-optimization
aggregation
Nikita BarsukovbyNikita Barsukov·Oct 30, 2024
TLDR

To group timestamps by day in SQL, use the CAST function to convert timestamps to a date. You can then aggregate records using GROUP BY with the date:

SELECT CAST(timestamp_column AS DATE) AS date_group, COUNT(*) AS daily_count FROM table_name GROUP BY date_group;

Don't forget to replace timestamp_column and table_name by your specifics. This groups records day-wise, ignoring the exact time of event.

Exploring the date functions in SQL

Every SQL dialect has its own way of parsing date and time. For instance, PostgreSQL uses DATE(), in MySQL you can use DATE_FORMAT() to customize the output format.

Timezone considerations

When counting timestamps by day, beware the ides of time zones. Deal with this by converting to a consistent time zone using AT TIME ZONE command.

About performance

If you are swimming in a sea of data, consider indexing the date conversions for better query performance.

Aggregates: More than just count

Counting events gives an overview, but to get more insight, consider other aggregation:

  • AVG(): The true average joe of metrics.
  • MAX()/MIN(): Everyone loves a record breaker, or maker.

Handling truncated sets

Without the full picture, comparing daily data can be skewed. If you have partial start or end days, filter these out, or make a note in the results.

Supercharged grouping methods

For those who love finely-sliced reports, level up your GROUP BY with:

  • ROLLUP: For the lovers of hierarchy.
  • CUBE: For those who need all the angles.
  • GROUPING SETS: To group, responsibly.