MySQL query to convert a string into a month (Number)?


Use the str_to_date() method −

select month(str_to_date(yourColumnName,'%b')) from yourTableName;

Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   MonthName varchar(100)
   );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(MonthName) values('Jan');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(MonthName) values('Mar');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement:
mysql> select *from DemoTable;

Output

+----+-----------+
| Id | MonthName |
+----+-----------+
| 1  | Jan       |
| 2  | Mar       |
+----+-----------+
2 rows in set (0.00 sec)

Following is the query to convert a string into a month (Number) −

mysql> select month(str_to_date(MonthName,'%b')) from DemoTable;

Output

+------------------------------------+
| month(str_to_date(MonthName,'%b')) |
+------------------------------------+
| 1                                  |
| 3                                  |
+------------------------------------+
2 rows in set (0.05 sec)
raja
Published on 14-Jun-2019 11:14:30
Advertisements