MySQL
SQL Queries
Data Aggregation
Date Functions
Database Management

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.

Practice system design

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:

sql
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;

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:

sql
SELECT DATE(sale_date) as sale_day, SUM(amount) as total_sales
FROM sales
GROUP BY DATE(sale_date);

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:

sql
SELECT DATE_FORMAT(sale_date, '%Y-%m') as sale_month, SUM(amount) as total_sales
FROM sales
GROUP BY YEAR(sale_date), MONTH(sale_date);

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:

sql
SELECT YEAR(sale_date) as sale_year, SUM(amount) as total_sales
FROM sales
GROUP BY YEAR(sale_date);

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():

sql
SELECT YEAR(sale_date) as sale_year, QUARTER(sale_date) as sale_quarter, SUM(amount) as total_sales
FROM sales
GROUP BY YEAR(sale_date), QUARTER(sale_date);

Dealing with Time Zones

If your database handles multiple time zones, make sure the datetime is converted to the desired one's before aggregation:

sql
SELECT CONVERT_TZ(sale_date, '+00:00', '+05:30') as sale_day_timezone, SUM(amount) as total_sales
FROM sales
GROUP BY DATE(CONVERT_TZ(sale_date, '+00:00', '+05:30'));

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 TypeFunction UsedExample Query Snippet
DailyDATE()GROUP BY DATE(sale_date)
MonthlyDATE_FORMAT('%Y-%m')GROUP BY YEAR(sale_date), MONTH(sale_date)
YearlyYEAR()GROUP BY YEAR(sale_date)
QuarterlyYEAR(), QUARTER()GROUP BY YEAR(sale_date), QUARTER(sale_date)
Custom Time ZoneCONVERT_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
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track 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.

Practice system design

All Rights Reserved.