MySQL query to select date >= current date - 3 weeks?


Use the concept of DATE_SUB(). Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ArrivalDate datetime
   );
Query OK, 0 rows affected (1.02 sec)

Note: Let’s say the current date is 2019-06-08

Insert some records in the table using insert command −

mysql> insert into DemoTable(ArrivalDate) values('2019-05-15');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ArrivalDate) values('2019-06-08');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(ArrivalDate) values('2019-05-20');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(ArrivalDate) values('2019-05-12');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+---------------------+
| Id | ArrivalDate         |
+----+---------------------+
| 1  | 2019-05-15 00:00:00 |
| 2  | 2019-06-08 00:00:00 |
| 3  | 2019-05-20 00:00:00 |
| 4  | 2019-05-12 00:00:00 |
+----+---------------------+
4 rows in set (0.00 sec)

Here is the query to select the dates, which are greater than equal to current date - 3 weeks −

mysql> select ArrivalDate from DemoTable where ArrivalDate> DATE_SUB(curdate(),INTERVAL 3 WEEK);

Output

+---------------------+
| ArrivalDate         |
+---------------------+
| 2019-06-08 00:00:00 |
| 2019-05-20 00:00:00 |
+---------------------+
2 rows in set (0.00 sec)
raja
Published on 14-Jun-2019 11:23:50
Advertisements