MySQL query to select rows older than a week?

MySQLMySQLi Database

For this, you can use DATEDIFF() function. The current date time is as follows −

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-06-09 19:15:56 |
+---------------------+
1 row in set (0.00 sec)

Let us first create a table −

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

Insert some records in the table using insert command −

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

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

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

mysql> insert into DemoTable values('2019-05-21');
Query OK, 1 row affected (0.24 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+---------------------+
| ShippingDate        |
+---------------------+
| 2019-06-01 00:00:00 |
| 2019-06-02 00:00:00 |
| 2019-06-14 00:00:00 |
| 2019-05-21 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)

Following is the query to select rows older than a week. Let’s say the current date is “2019-06-09”. Therefore, the rows would get selected older than a week i.e. before “2019-06-02” −

mysql> select *from DemoTable where DATEDIFF(now(),ShippingDate) > 7;

Output

+---------------------+
| ShippingDate        |
+---------------------+
| 2019-06-01 00:00:00 |
| 2019-05-21 00:00:00 |
+---------------------+
2 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 12:32:08
Advertisements