MySQL Query GROUP BY day / month / year
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Data aggregation is a common requirement in database management, and MySQL provides various ways to aggregate data using the GROUP BY clause. When handling time-series data, grouping by day, month, or year becomes particularly useful for calculations that involve summarizing data over specific time periods. This article covers how to use the GROUP BY clause in MySQL to aggregate data by day, month, and year, providing detailed explanations and examples of each scenario.
Basic Syntax of GROUP BY
The GROUP BY statement is utilized in SQL to arrange identical data into groups. Along with aggregate functions (like COUNT, SUM, AVG), it allows for summarizing data based on one or more columns. The basic syntax is:
Here, column1 is usually the column by which you want to group the records, and aggregate_function(column2) is the operation you wish to carry out on another column.
Grouping by Day
When data includes a timestamp, it is often useful to visualize or calculate statistics per day. To group records by day, you typically use the DATE() function, which extracts the date part from a datetime or timestamp column.
Example
Let's assume we have a sales table with the columns id, amount, and sale_date. To get the total sales for each day, you can write the query as follows:
This query will produce a list of days along with the total sales for each day.
Grouping by Month
Grouping by month is slightly more complex because the DATE_FORMAT function is needed to strip the day part and maintain the year and month only.
Example
In the same sales table, to summarize monthly sales, you'd use:
This query will show the total sales per month in the YYYY-MM format.
Grouping by Year
Aggregating data by year typically involves only the YEAR() function, which extracts the year from a date.
Example
To see annual sales data:
This results in a yearly total of sales data, useful for generating annual reports.
Handling Complex Date Groupings
Combining Aggregations
MySQL allows you to combine these groupings. For instance, if you want quarterly data, you can use both YEAR() and QUARTER():
Dealing with Time Zones
If your database handles multiple time zones, make sure the datetime is converted to the desired one's before aggregation:
This query accounts for time zone differences by converting the UTC time to the desired time zone (+05:30 in the example).
Summary Table
The table below summarizes key GROUP BY methods discussed for date-based aggregation:
| Aggregation Type | Function Used | Example Query Snippet |
| Daily | DATE() | GROUP BY DATE(sale_date) |
| Monthly | DATE_FORMAT('%Y-%m') | GROUP BY YEAR(sale_date), MONTH(sale_date) |
| Yearly | YEAR() | GROUP BY YEAR(sale_date) |
| Quarterly | YEAR(), QUARTER() | GROUP BY YEAR(sale_date), QUARTER(sale_date) |
| Custom Time Zone | CONVERT_TZ() | GROUP BY DATE(CONVERT_TZ(...)) |
Conclusion
Aggregating data by time intervals using the GROUP BY clause enhances analysis capabilities in MySQL. By understanding how to manipulate date functions, you can derive meaningful insights from your datasets based on daily, monthly, or yearly divisions. Employing date conversions and timezone adjustments can further augment your queries to handle complex datasets with precision.
Related reading
- MySQL query String contains
- MySQL query to get column names?
- MySQL Query to select data from last week?
- MySQL Quick breakdown of the types of joins
- Mysql remote connect over ssh to a kubernetes pod
- MySQL remove all whitespaces from the entire column
- MySQL Removing Some Foreign keys
- Mysql Replication, 2 databases, 2 ways?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.