- 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
MySQL query to return all records with a datetime older than 1 week
To get dates older than 1 week, you can use the following syntax −
select *from yourTableName where yourColumnName < now() - interval 1 week;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table DatesOfOneWeek −> ( −> ArrivalTime datetime −> ); Query OK, 0 rows affected (0.87 sec)
Insert some records in the table −
mysql> insert into DatesOfOneWeek values(date_add(now(),interval 2 week)); Query OK, 1 row affected (0.11 sec) mysql> insert into DatesOfOneWeek values('2018-11-04'); Query OK, 1 row affected (0.14 sec) mysql> insert into DatesOfOneWeek values('2018-11-25'); Query OK, 1 row affected (0.11 sec) mysql> insert into DatesOfOneWeek values(date_add(now(),interval -1 week)); Query OK, 1 row affected (0.14 sec) mysql> insert into DatesOfOneWeek values(date_add(now(),interval 1 week)); Query OK, 1 row affected (0.11 sec)
Let us check the records which we have inserted above are present or not. The query to display all records from the table is as follows −
mysql> select *from DatesOfOneWeek;
The following is the output −
+---------------------+ | ArrivalTime | +---------------------+ | 2018-12-20 18:11:02 | | 2018-11-04 00:00:00 | | 2018-11-25 00:00:00 | | 2018-11-29 18:11:40 | | 2018-12-13 18:11:46 | +---------------------+ 5 rows in set (0.00 sec)
Here is the MySQL query to get a date which was in the past i.e. all the date before 1 week −
mysql> select *from DatesOfOneWeek where ArrivalTime < now() - interval 1 week;
The following is the output −
+---------------------+ | ArrivalTime | +---------------------+ | 2018-11-04 00:00:00 | | 2018-11-25 00:00:00 | | 2018-11-29 18:11:40 | +---------------------+ 3 rows in set (0.00 sec)
Advertisements