MySQL query to select records from a table on the basis of a particular month number?

MySQLMySQLi Database

You can select specific month with the help of MONTH() function. The syntax is as follows −

SELECT yourColumnName FROM yourTableName WHERE MONTH(yourColumnName) = yourValue;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table UserLoginTimeInformation
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserLoginDatetime datetime
   -> );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values(date_add(now(), interval 3 month));
Query OK, 1 row affected (0.14 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2013-05-13 13:45:34');
Query OK, 1 row affected (0.17 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2013-06-11 12:41:04');
Query OK, 1 row affected (0.19 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2012-05-25 15:03:24');
Query OK, 1 row affected (0.23 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2017-05-21 12:12:40');
Query OK, 1 row affected (0.10 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2018-09-29 11:30:34');
Query OK, 1 row affected (0.10 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2016-03-10 16:40:45');
Query OK, 1 row affected (0.27 sec)

Display all records from the table using a select statement. The query is as follows −

mysql> select *from UserLoginTimeInformation;

The following is the output −

+--------+---------------------+
| UserId | UserLoginDatetime   |
+--------+---------------------+
| 1 | 2019-05-13 15:01:24 |
| 2 | 2013-05-13 13:45:34 |
| 3 | 2013-06-11 12:41:04 |
| 4 | 2012-05-25 15:03:24 |
| 5 | 2017-05-21 12:12:40 |
| 6 | 2018-09-29 11:30:34 |
| 7 | 2016-03-10 16:40:45 |
+--------+---------------------+
7 rows in set (0.00 sec)

Example

Here is the query to select all the records from the table on the basis of month number −

mysql> select UserLoginDatetime from UserLoginTimeInformation where MONTH(UserLoginDatetime) = 5;

Output

+---------------------+
| UserLoginDatetime |
+---------------------+
| 2019-05-13 15:01:24 |
| 2013-05-13 13:45:34 |
| 2012-05-25 15:03:24 |
| 2017-05-21 12:12:40 |
+---------------------+
4 rows in set (0.00 sec)
raja
Published on 19-Mar-2019 08:30:12
Advertisements