- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the difference between dates in the form of months with MySQL
Let us first create a table −
mysql> create table DemoTable -> ( -> Date1 date, -> Date2 date -> ); Query OK, 0 rows affected (1.04 sec)
Insert some records in the table using insert command &miuns;
mysql> insert into DemoTable values('2017-01-10','2017-12-10'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('2018-12-31','2015-01-02'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('2020-03-01','2019-06-15'); Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+------------+ | Date1 | Date2 | +------------+------------+ | 2017-01-10 | 2017-12-10 | | 2018-12-31 | 2015-01-02 | | 2020-03-01 | 2019-06-15 | +------------+------------+ 3 rows in set (0.00 sec)
Here is the query to find the difference between dates in the form of months −
mysql> select abs(timestampdiff(MONTH,Date1,Date2)) from DemoTable;
This will produce the following output −
+---------------------------------------+ | abs(timestampdiff(MONTH,Date1,Date2)) | +---------------------------------------+ | 11 | | 47 | | 8 | +---------------------------------------+ 3 rows in set (0.03 sec)
Advertisements