How to Group By Hour in MySQL
Robert Cooper
Robert CooperSenior Software Engineer
· January 31, 2025

Robert Cooper
Robert CooperSenior Software Engineer
· January 31, 2025

Grouping data by hour in MySQL involves extracting the hour part from a datetime or timestamp column and using it in a GROUP BY clause. The technique is common in time series analysis for aggregating data into hourly intervals.
MySQL’s HOUR() function extracts the hour from a time value, which makes it the basis for grouping data by hour. The basic syntax looks like this:
SELECT HOUR(time_column) AS hour
FROM your_table;
To group records by hour, use the HOUR() function within the GROUP BY clause. This approach aggregates data for each hour of the day (0-23).
SELECT HOUR(datetime_column) AS hour, COUNT(*)
FROM your_table
GROUP BY HOUR(datetime_column);
When dealing with timestamps, you often need to group by both the date and the hour to avoid mixing data from different days.
SELECT DATE(datetime_column) AS date, HOUR(datetime_column) AS hour, COUNT(*)
FROM your_table
GROUP BY DATE(datetime_column), HOUR(datetime_column);
If your data involves different time zones, convert the datetime to a consistent time zone before grouping.
SELECT CONVERT_TZ(datetime_column, '+00:00', your_timezone) AS converted_time
FROM your_table;
Then, use converted_time for grouping.
Combine the GROUP BY clause with aggregate functions like SUM(), AVG(), or COUNT() to summarize data.
SELECT HOUR(datetime_column) AS hour, SUM(value_column)
FROM your_table
GROUP BY HOUR(datetime_column);
To filter within a specific date range, combine WHERE with GROUP BY.
SELECT HOUR(datetime_column) AS hour, COUNT(*)
FROM your_table
WHERE datetime_column BETWEEN '2023-01-01' AND '2023-01-31'
GROUP BY HOUR(datetime_column);
If this query pattern is part of recurring reporting, Basedash helps you turn it into reusable, AI-native BI workflows: prompt-to-SQL, shared dashboards, and trusted answers that stay aligned with your data model.
Written by

Senior Software Engineer
Robert Cooper is a senior engineer who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.