MySQL query to fetch records wherein timestamp is before 15+ days?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> ArrivalDate datetime
   -> );
Query OK, 0 rows affected (0.91 sec)

Insert some records in the table using insert command. Let’s say the current date is 2019-07-03 −

mysql> insert into DemoTable values('2019-07-03');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('2019-06-20');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2019-06-15');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('2018-06-11');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('2018-06-01');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+
| ArrivalDate         |
+---------------------+
| 2019-07-03 00:00:00 |
| 2019-06-20 00:00:00 |
| 2019-06-15 00:00:00 |
| 2018-06-11 00:00:00 |
| 2018-06-01 00:00:00 |
+---------------------+
5 rows in set (0.00 sec)

Following is the query to fetch records wherein timestamp is 15+ days ago −

mysql> select *from DemoTable where ArrivalDate < date_sub(now(), interval 15 day) order by ArrivalDate DESC;

This will produce the following output −

+---------------------+
| ArrivalDate         |
+---------------------+
| 2019-06-15 00:00:00 |
| 2018-06-11 00:00:00 |
| 2018-06-01 00:00:00 |
+---------------------+
3 rows in set (0.00 sec)
raja
Published on 11-Jul-2019 15:05:17
Advertisements