EN
MySQL - group rows by year
0
points
In this article, we would like to show you how to group rows by year in MySQL.
Quick solution:
SELECT
DATE_FORMAT(`datetime_column_name`, '%Y') as `alias_name`
FROM `table_name`
GROUP BY YEAR(`datetime_column_name`);
Practical example
To show how to group rows by year, we will use the following table:
Note:
At the end of this article you can find database preparation SQL queries.
Example
In this example, we will display all the years from the users
table grouped, so we don't get any duplicates.
Query:
SELECT
DATE_FORMAT(`registration_time`, '%Y') as `date`
FROM `users`
GROUP BY YEAR(`registration_time`) DESC;
Result:
Note:
Go to this article to read how to count rows per year.
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','2020-03-03 22:35:38'),
('Kate','2019-04-04 22:46:51'),
('Nam','2019-04-04 22:57:37');