Get Month Name from Month number in MySQL?


You can use MONTHNAME() function from MySQL to display Month name from number. The syntax is as follows.

SELECT MONTHNAME(STR_TO_DATE(yourColumnName,’%m’)) as anyVariableName from yourTableName;

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

mysql> create table MonthDemo
-> (
-> MonthNum int
-> );
Query OK, 0 rows affected (0.87 sec)

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

mysql> insert into MonthDemo values(1);
Query OK, 1 row affected (0.14 sec)

mysql> insert into MonthDemo values(2);
Query OK, 1 row affected (0.15 sec)

mysql> insert into MonthDemo values(3);
Query OK, 1 row affected (0.12 sec)

mysql> insert into MonthDemo values(4);
Query OK, 1 row affected (0.12 sec)

mysql> insert into MonthDemo values(5);
Query OK, 1 row affected (0.13 sec)

mysql> insert into MonthDemo values(6);
Query OK, 1 row affected (0.18 sec)

mysql> insert into MonthDemo values(7);
Query OK, 1 row affected (0.13 sec)

mysql> insert into MonthDemo values(8);
Query OK, 1 row affected (0.13 sec)

mysql> insert into MonthDemo values(9);
Query OK, 1 row affected (0.15 sec)

mysql> insert into MonthDemo values(10);
Query OK, 1 row affected (0.13 sec)

mysql> insert into MonthDemo values(11);
Query OK, 1 row affected (0.14 sec)

mysql> insert into MonthDemo values(12);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select command. The query is as follows.

mysql> select *from MonthDemo;

The following is the output.

+------------+
| MonthNum   |
+------------+
| 1          |
| 2          |
| 3          |
| 4          |
| 5          |
| 6          |
| 7          |
| 8          |
| 9          |
| 10         |
| 11         |
| 12         |
+------------+
12 rows in set (0.00 sec)

Here is the query to display month name.

mysql> select monthname(str_to_date(MonthNum,'%m')) as MonthName from MonthDemo;

The following is the output.

+-----------+
| MonthName |
+-----------+
| January   |
| February  |
| March     |
| April     |
| May       |
| June      |
| July      |
| August    |
| September |
| October   |
| November  |
| December  |
+-----------+
12 rows in set (0.00 sec)

Updated on: 25-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements