Extract the month and year in the following format: “mm-yyyy” (month year) along with all columns in MySQL?


For month and year in a specific format, use DATE_FORMAT() along with STR_TO_DATE(). Let us first create a table −

mysql> create table DemoTable1931
   (
   ShippingDate varchar(40)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1931 values('10-11-2017');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('31-01-2019');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('02-02-2018');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('10-06-2013');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1931;

This will produce the following output −

+--------------+
| ShippingDate |
+--------------+
| 10-11-2017   |
| 31-01-2019   |
| 02-02-2018   |
| 10-06-2013   |
+--------------+
4 rows in set (0.00 sec)

Following is the query to extract the month and year in the format “mm-yyyy”, along with all columns −

mysql> select date_format(str_to_date(ShippingDate,'%d-%m-%Y'),'%m-%Y') from DemoTable1931;

This will produce the following output −

+-----------------------------------------------------------+
| date_format(str_to_date(ShippingDate,'%d-%m-%Y'),'%m-%Y') |
+-----------------------------------------------------------+
| 11-2017                                                   |
| 01-2019                                                   |
| 02-2018                                                   |
| 06-2013                                                   |
+-----------------------------------------------------------+
4 rows in set (0.00 sec)

Updated on: 30-Dec-2019

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements