
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find out number of days in a month in MySQL?
To find the number of days in month, use the below syntax.
select DAY(LAST_DAY(yourColumnName)) 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 DaysInaGivenMonth -> ( -> MonthName datetime -> ); Query OK, 0 rows affected (1.62 sec)
Insert some records in the table using insert command. The query is as follows.
mysql> insert into DaysInaGivenMonth values(now()); Query OK, 1 row affected (0.24 sec) mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -1 month)); Query OK, 1 row affected (0.16 sec) mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -2 month)); Query OK, 1 row affected (0.10 sec) mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -3 month)); Query OK, 1 row affected (0.20 sec) mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -4 month)); Query OK, 1 row affected (0.23 sec) mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -5 month)); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from DaysInaGivenMonth;
The following is the output.
+---------------------+ | MonthName | +---------------------+ | 2019-01-01 21:34:26 | | 2018-12-01 21:34:55 | | 2018-11-01 21:35:14 | | 2018-10-01 21:35:20 | | 2018-09-01 21:35:23 | | 2018-08-01 21:35:27 | +---------------------+ 6 rows in set (0.00 sec)
Here is the query to find out the number of days in the months listed above.
mysql> select DAY(LAST_DAY(MonthName)) as DaysInMonth from DaysInaGivenMonth;
The following is the output.
+-------------+ | DaysInMonth | +-------------+ | 31 | | 31 | | 30 | | 31 | | 30 | | 31 | +-------------+ 6 rows in set (0.00 sec)
Advertisements