Fetch datetime row from exactly past 7 days records in MySQL

MySQLMySQLi Database

For this, you can use the INTERVAL 7 day concept. Let us first create a table −

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

Note − Let’s say the current date is 2019-08-23.

Insert some records in the table using insert command −

mysql> insert into DemoTable(AdmissionDate) values('2019-01-23');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(AdmissionDate) values('2019-08-15');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(AdmissionDate) values('2019-08-16');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(AdmissionDate) values('2019-08-24');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+---------------------+
| Id | AdmissionDate       |
+----+---------------------+
|  1 | 2019-01-23 00:00:00 |
|  2 | 2019-08-15 00:00:00 |
|  3 | 2019-08-16 00:00:00 |
|  4 | 2019-08-24 00:00:00 |
+----+---------------------+
4 rows in set (0.00 sec)

Here is the query to fetch DateTime row from exactly past 7 days records −

mysql> select *from DemoTable where date(AdmissionDate)=CURDATE() - interval 7 day;

This will produce the following output −

+----+---------------------+
| Id | AdmissionDate       |
+----+---------------------+
|  3 | 2019-08-16 00:00:00 |
+----+---------------------+
1 row in set (0.04 sec)
raja
Published on 30-Sep-2019 10:43:27
Advertisements