Grab where current date and the day before with MySQL?


You can grab the current date with CURDATE() and the day before with MySQL using DATE_SUB() with INTERVAL 1 DAY. The syntax is as follows:

SELECT DATE_SUB(CURDATE(),INTERVAL 1 DAY);

The syntax is as follows to get curdate and the day before with date_sub().

SELECT *FROM yourTableName WHERE yourColumnName = CURDATE() OR yourColumnName = DATE_SUB(CURDATE(),INTERVAL 1 DAY);

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table ProductDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(20),
   -> ProductOfferDate datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command. Here, we have added the products and the product offer date. The query is as follows:

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-11','2017-05-21');
Query OK, 1 row affected (0.25 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-22','2019-01-15');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-21','2019-01-14');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-91','2018-10-23');
Query OK, 1 row affected (0.26 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-133','2019-01-24');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement. The query is as follows:

mysql> select *from ProductDemo;

The following is the output:

+----+-------------+---------------------+
| Id | ProductName | ProductOfferDate    |
+----+-------------+---------------------+
| 1 | Product-11 | 2017-05-21 00:00:00 |
| 2 | Product-22 | 2019-01-15 00:00:00 |
| 3 | Product-21 | 2019-01-14 00:00:00 |
| 4 | Product-91 | 2018-10-23 00:00:00 |
| 5 | Product-133 | 2019-01-24 00:00:00 |
+----+-------------+---------------------+
5 rows in set (0.00 sec)

The following is the query to grab the product with current date and the day before:

mysql> select *from ProductDemo
   -> where ProductOfferDate = CURDATE() OR ProductOfferDate = date_sub(curdate(),interval 1 day);

The following is the output:

+----+-------------+---------------------+
| Id | ProductName | ProductOfferDate    |
+----+-------------+---------------------+
|  2 | Product-22  | 2019-01-15 00:00:00 |
|  3 | Product-21  | 2019-01-14 00:00:00 |
+----+-------------+---------------------+
2 rows in set (0.00 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements