Group by month and year in MySQL
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
When working with time-series data in a MySQL database, it’s often useful to aggregate data on a monthly basis or by year. This can help identify trends, patterns, or simply make sense of large amounts of time-indicated data. Grouping by month and year in MySQL typically involves using date functions to extract the year and month, then performing aggregation operations such as COUNT, SUM, AVG, etc.
Date and Time Functions in MySQL
MySQL provides various date and time functions that you can use to extract specific portions of dates. Here are a few important ones:
YEAR(date): Extracts the year from a date.MONTH(date): Extracts the month from a date.DATE_FORMAT(date, format): Formats the date according to the specified format.MONTHNAME(date): Returns the month name of a date.
These functions are instrumental when grouping by specific time frames such as year and month.
Grouping By Month and Year
To efficiently group records by month and year, you can use the YEAR()
and MONTH()
functions within the GROUP BY
clause. Below is an example to demonstrate this approach.
Example
Imagine you have a table named orders
with the following structure:
| id | order_date | amount |
| 1 | 2023-01-15 | 100 |
| 2 | 2023-01-20 | 150 |
| 3 | 2023-02-15 | 200 |
| 4 | 2023-03-10 | 300 |
| 5 | 2023-03-25 | 250 |
| ... | ... | ... |
To get the total sales amount grouped by month and year, the SQL query would look like this:
- Indexes: Index the
order_datefield to speed up sorting and grouping operations. - Partitioning: If the dataset is extremely large, consider partitioning the table by year or month.
- Use Specific Columns: Always specify the exact columns you need in the
SELECTclause to minimize data processing and transfer. - Null Dates: Ensure there are no nulls in
order_date, or use methods to handle nulls to avoid unexpected results. - Time Zones: Be aware of and handle any time zone differences if your source data comes from a range of time zones.
Related reading
- Group by with multiple columns using lambda
- Group detection in data sets
- Group n points in k clusters of equal size
- GroupBy pandas DataFrame and select most common value
- GROUP_CONCAT comma separator
- GROUP_CONCAT ORDER BY
- Grouping functions (tapply, by, aggregate) and the *apply family
- Grouping numbers based on occurrences?

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.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.