Select data and set value to boolean based on timestamp column in MySQL


For this, use IF(). Let us first see the current date −

mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2019-12-10 |
+------------+
1 row in set (0.00 sec)

Let us first create a table −

mysql> create table DemoTable1890
   (
   DueDate timestamp
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1890 values('2017-12-10');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1890 values('2021-12-10');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1890 values('2018-04-24');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1890 values('2020-05-11');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1890;

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 2017-12-10 00:00:00 |
| 2021-12-10 00:00:00 |
| 2018-04-24 00:00:00 |
| 2020-05-11 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)

Here is the query to select data and set value based on timestamp column −

mysql> select if(DueDate > curdate() - interval 2 year,false,true) as Status from DemoTable1890;

This will produce the following output −

+--------+
| Status |
+--------+
|      1 |
|      0 |
|      0 |
|      0 |
+--------+
4 rows in set (0.00 sec)

Updated on: 27-Dec-2019

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements