SQL Cookbook Lesson
How to group by month in SQL
Learn how to group by month in SQL with examples and explanations from SQLPad.
Problem
You have a database with a date field and you want to group all entries by the month of that date.
Sample Data
Let's consider a table called Orders with the following data:
| OrderId | Product | OrderDate |
|---|---|---|
| 1 | Apple | 2021-01-15 |
| 2 | Banana | 2021-02-20 |
| 3 | Orange | 2021-02-25 |
| 4 | Apple | 2021-03-10 |
| 5 | Banana | 2021-03-15 |
MySQL Solution
SELECT MONTH(OrderDate) as Month, COUNT(*) as TotalOrders
FROM Orders
GROUP BY MONTH(OrderDate);
Explanation (MySQL)
In this MySQL query, the MONTH() function is used to extract the month from the OrderDate field. The GROUP BY clause then groups the result-set by the month. The COUNT(*) function is used to get the number of orders per month.
PostgreSQL Solution
SELECT EXTRACT(MONTH FROM OrderDate) as Month, COUNT(*) as TotalOrders
FROM Orders
GROUP BY EXTRACT(MONTH FROM OrderDate);
Explanation (PostgreSQL)
In the PostgreSQL query, the EXTRACT(MONTH FROM OrderDate) function is used which works similarly to the MONTH() function in MySQL. It extracts the month from the OrderDate field. The GROUP BY clause is used to group the result-set by the month. The COUNT(*) function is used to get the number of orders per month.