Want to fetch only the month part from a date in MySQL

MySQLMySQLi Database

To fetch only the month part, use DATE_FORMAT().

Let us first create a table −

mysql> create table DemoTable753 (DueDate datetime);
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable753 values('2019-06-21');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable753 values('2019-01-31');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable753 values('2018-12-01');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable753 values('2016-11-11');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable753;

This will produce the following output -

+---------------------+
| DueDate             |
+---------------------+
| 2019-06-21 00:00:00 |
| 2019-01-31 00:00:00 |
| 2018-12-01 00:00:00 |
| 2016-11-11 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)

Following is the query to fetch only the month part from a date in MySQL −

mysql> select date_format(DueDate,'%M'),date_format(DueDate,'%m') from DemoTable753;

This will produce the following output -

+---------------------------+---------------------------+
| date_format(DueDate,'%M') | date_format(DueDate,'%m') |
+---------------------------+---------------------------+
| June                      | 06                        |
| January                   | 01                        |
| December                  | 12                        |
| November                  | 11                        |
+---------------------------+---------------------------+
4 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 07:50:04
Advertisements