How to select month and year from dates in MySQL?

MySQLMySQLi Database

To select month and year in MySQL, you can use MONTH() and YEAR() method. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> DueDate datetime
   -> );
Query OK, 0 rows affected (0.90 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-01-21');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values('2019-06-15');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2018-12-01');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2015-04-01');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2016-08-14');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql− select *from DemoTable;

Output

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 2019-01-21 00:00:00 |
| 2019-06-15 00:00:00 |
| 2018-12-01 00:00:00 |
| 2015-04-01 00:00:00 |
| 2016-08-14 00:00:00 |
+---------------------+
5 rows in set (0.00 sec)

Following is the query to select month and year from MySQL −

mysql> select MONTH(DueDate) AS MONTH, YEAR(DueDate) AS YEAR from DemoTable;

Output

This will produce the following output −

+-------+------+
| MONTH | YEAR |
+-------+------+
| 1     | 2019 |
| 6     | 2019 |
| 12    | 2018 |
| 4     | 2015 |
| 8     | 2016 |
+-------+------+
5 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 14:27:08
Advertisements