- 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
How to compare the first date and the last date from a MySQL column with date records?
To compare the first date with the last date, use TIME_TO_SEC() along with MAX() and MIN(). Let us first create a table −
mysql> create table DemoTable ( UserName varchar(100), UserPostDatetime datetime ); Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Adam','2019-08-24 11:10:00'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Adam','2019-08-24 11:20:00'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Adam','2019-08-24 11:50:00'); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+---------------------+ | UserName | UserPostDatetime | +----------+---------------------+ | Adam | 2019-08-24 11:10:00 | | Adam | 2019-08-24 11:20:00 | | Adam | 2019-08-24 11:50:00 | +----------+---------------------+ 3 rows in set (0.00 sec)
Following is the query to compare the first date and the last date −
mysql> select UserName,sec_to_time(max(time_to_sec(UserPostDatetime))-min(time_to_sec(UserPostDatetime)))t from DemoTable group by UserName;
This will produce the following output −
+----------+----------+ | UserName | t | +----------+----------+ | Adam | 00:40:00 | +----------+----------+ 1 row in set (0.03 sec)
Advertisements