How to update column values with date records and set 1 for corresponding records before the current date in SQL


Let’s say the current date is 2019-08-20. Now for our example, we will create a table −

mysql> create table DemoTable
(
   ProductStatus tinyint(1),
   ProductExpiryDate date
);
Query OK, 0 rows affected (1.03 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(0,'2019-06-12');
Query OK, 1 row affected (0.43 sec)
mysql> insert into DemoTable values(0,'2019-10-11');
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable values(0,'2018-07-24');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(0,'2018-09-05');
Query OK, 1 row affected (0.27 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------+-------------------+
| ProductStatus | ProductExpiryDate |
+---------------+-------------------+
| 0             | 2019-06-12        |
| 0             | 2019-10-11        |
| 0             | 2018-07-24        |
| 0             | 2018-09-05        |
+---------------+-------------------+
4 rows in set (0.00 sec)

Following is the query to set value 1 for records before the current date

mysql> update DemoTable
   set ProductStatus=1
   where ProductExpiryDate <=CURDATE();
Query OK, 3 rows affected (0.95 sec)
Rows matched : 3 Changed : 3 Warnings : 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+---------------+-------------------+
| ProductStatus | ProductExpiryDate |
+---------------+-------------------+
| 1             | 2019-06-12        |
| 0             | 2019-10-11        |
| 1             | 2018-07-24        |
| 1             | 2018-09-05        |
+---------------+-------------------+
4 rows in set (0.00 sec)

Updated on: 07-Oct-2019

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements