
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Select Rows Older Than a Week
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)
Advertisements