How to get first day of every corresponding month in MySQL?


You can use date-format() function from MySQL to get the first day of every corresponding month. The syntax is as follows −

select DATE_FORMAT(yourDatetimeColumnName ,'%Y-%m-01') as anyVariableName from
yourTableName;

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

mysql> create table getFirstDayOfMonth
   -> (
   -> DueDatetime datetime
   -> );
Query OK, 0 rows affected (1.16 sec)

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

mysql> insert into getFirstDayOfMonth values(date_add(now(),interval 3 month));
Query OK, 1 row affected (0.30 sec)

mysql> insert into getFirstDayOfMonth values(date_add(now(),interval -3 month));
Query OK, 1 row affected (0.13 sec)

mysql> insert into getFirstDayOfMonth values(date_add(now(),interval -2 month));
Query OK, 1 row affected (0.18 sec)

mysql> insert into getFirstDayOfMonth values(date_add(now(),interval -1 month));
Query OK, 1 row affected (0.16 sec)

mysql> insert into getFirstDayOfMonth values(date_add(now(),interval -4 month));
Query OK, 1 row affected (0.10 sec)

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

mysql> select *from getFirstDayOfMonth;

Output

+---------------------+
| DueDatetime         |
+---------------------+
| 2019-03-20 12:32:06 |
| 2018-09-20 12:32:16 |
| 2018-10-20 12:32:22 |
| 2018-11-20 12:32:28 |
| 2018-08-20 12:32:33 |
+---------------------+
5 rows in set (0.00 sec)

Here is the query to get the first day of corresponding month. Whatever month is in the column, the following query will return the first day of each of that month −

mysql> select DATE_FORMAT(DueDatetime ,'%Y-%m-01') as DateDemo from getFirstDayOfMonth;

Output

+------------+
| DateDemo   |
+------------+
| 2019-03-01 |
| 2018-09-01 |
| 2018-10-01 |
| 2018-11-01 |
| 2018-08-01 |
+------------+
5 rows in set (0.00 sec)

Updated on: 30-Jul-2019

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements