Languages
[Edit]
EN

MySQL - count rows per month

0 points
Created by:
Dharman
518

In this article, we would like to show you how to count rows per month in MySQL.

Quick solution:

SELECT
    DATE_FORMAT(`datetime_column_name`, '%Y-%m') as `alias_name1`,
    COUNT(*) as `alias_name2`
FROM `table_name`
GROUP BY MONTH(`datetime_column_name`)
ORDER BY `alias_name2` DESC;

Practical example

To show how to count rows per month, we will use the following table:

MySQL - example data used to count rows per month
MySQL - example data used to count rows per month

Note:

At the end of this article you can find database preparation SQL queries.

Example

In this example, we will display the month number and the number of registered users for each month in descending order.

Query:

SELECT
    DATE_FORMAT(`registration_time`, '%Y-%m') as `date`,
    COUNT(*) as `count`
FROM `users`
GROUP BY MONTH(`registration_time`)
ORDER BY `count` DESC;

Result:

MySQL - count rows per month - result
MySQL - count rows per month - result

Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`username` VARCHAR(50) NOT NULL,
	`registration_time` DATETIME NOT NULL,
	PRIMARY KEY (`id`)
);

insert_data.sql file:

INSERT INTO `users`
	(`username`, `registration_time`)
VALUES
	('Tom', '2021-01-01 11:41:31'),
	('Chris','2021-02-02 11:42:45'),
	('Jack','2021-03-03 15:13:39'),
    ('Kim','2021-03-03 15:24:51'),
    ('Marco','2021-03-03 22:35:38'),
	('Kate','2021-04-04 22:46:51'),
	('Nam','2021-04-04 22:57:37');
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MySQL - dates

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join