Selecting data from a MySQL table based on a specific month?


Use the MONTH() method in MySQL to select date based on month. Let us first create a table −

mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(10),
-> UserPostMessageDate datetime,
-> UserLikes int
-> );
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes)
values('John','2019-01-31',4560);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes)
values('Sam','2019-06-28',790);
Query OK, 1 row affected (0.27 sec)

mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes)
values('Carol','2019-05-01',230);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes)
values('David','2019-03-05',10000000);
Query OK, 1 row affected (0.33 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----+----------+---------------------+-----------+
| Id | UserName | UserPostMessageDate | UserLikes |
+----+----------+---------------------+-----------+
| 1  | John     | 2019-01-31 00:00:00 | 4560      |
| 2  | Sam      | 2019-06-28 00:00:00 | 790       |
| 3  | Carol    | 2019-05-01 00:00:00 | 230       |
| 4  | David    | 2019-03-05 00:00:00 | 10000000  |
+----+----------+---------------------+-----------+
4 rows in set (0.00 sec)

Following is the query to select data from a table based on a specific month −

mysql> select Id,UserName,UserLikes from DemoTable where MONTH(UserPostMessageDate)=6;

Output

This will produce the following output −

+----+----------+-----------+
| Id | UserName | UserLikes |
+----+----------+-----------+
| 2  | Sam      | 790       |
+----+----------+-----------+
1 row in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements