How to select between/before/after dates in MySQL conditionally?

MySQLMySQLi Database

Following is the syntax −

select *from yourTableName
where
yourColumnName1 < yourValue1 AND
(yourColumnName2 > yourValue2 OR yourColumnName2 is null);

Let us create a table −

mysql> create table demo35
−> (
−> id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
−> joining_date date,
−> relieving_date date
−> );
Query OK, 0 rows affected (3.88 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo35(joining_date,relieving_date) values('2020−01−10','2020−07−11');
Query OK, 1 row affected (0.15 sec)
mysql> insert into demo35(joining_date,relieving_date) values('2020−05−07','2020−12−08');
Query OK, 1 row affected (0.17 sec)
mysql> insert into demo35(joining_date,relieving_date) values('2020−04−11','2020−09−18');
Query OK, 1 row affected (0.14 sec)
mysql> insert into demo35(joining_date,relieving_date) values('2020−03−12','2020−10−01');
Query OK, 1 row affected (0.13 sec)

Display records from the table using select statement −

mysql> select *from demo35;

This will produce the following output −

+----+--------------+----------------+
| id | joining_date | relieving_date |
+----+--------------+----------------+
|  1 | 2020−01−10   | 2020−07−11     |
|  2 | 2020−05−07   | 2020−12−08     |
|  3 | 2020−04−11   | 2020−09−18     |
|  4 | 2020−03−12   | 2020−10−01     |
+----+--------------+----------------+
4 rows in set (0.00 sec)

Following is the query to select date conditionally in MySQL −

mysql> select *from demo35
−> where
−> joining_date < '2020−05−11' AND
−> (relieving_date > '2020−08−10' OR relieving_date is null);

This will produce the following output −

+----+--------------+----------------+
| id | joining_date | relieving_date |
+----+--------------+----------------+
|  2 | 2020−05−07   | 2020−12−08     |
|  3 | 2020−04−11   | 2020−09−18     |
|  4 | 2020−03−12   | 2020−10−01     |
+----+--------------+----------------+
3 rows in set (0.00 sec)
raja
Published on 19-Nov-2020 12:38:05
Advertisements