How to select record from last 6 months in a news table using MySQL?

MySQLMySQLi Database

To select the last 6 months records from news table, use the date_sub() function from MySQL since news records are arranged according to date.

The syntax is as follows −

select *from yourTableName where yourDateTimeColumnName >= date_sub(now(),interval 6 month);

To understand the above concept, let us first create a NEWS table with only NEWS ID and the date on which it published −

mysql> create table Newstable
   -> (
   -> NewsId int,
   -> NewsDatetime datetime
   -> );
Query OK, 0 rows affected (0.66 sec)

Insert records in the table using insert command. The query is as follows −

mysql> insert into Newstable values(101,'2018-2-10');
Query OK, 1 row affected (0.18 sec)

mysql> insert into Newstable values(102,'2018-12-10');
Query OK, 1 row affected (0.19 sec)

mysql> insert into Newstable values(103,'2018-3-14');
Query OK, 1 row affected (0.14 sec)

mysql> insert into Newstable values(104,'2018-12-12');
Query OK, 1 row affected (0.29 sec)

mysql> insert into Newstable values(105,'2018-4-21');
Query OK, 1 row affected (0.09 sec)

mysql> insert into Newstable values(106,'2018-6-30');
Query OK, 1 row affected (0.22 sec)

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

mysql> select *from Newstable;

Output

+--------+---------------------+
| NewsId | NewsDatetime        |
+--------+---------------------+
|    101 | 2018-02-10 00:00:00 |
|    102 | 2018-12-10 00:00:00 |
|    103 | 2018-03-14 00:00:00 |
|    104 | 2018-12-12 00:00:00 |
|    105 | 2018-04-21 00:00:00 |
|    106 | 2018-06-30 00:00:00 |
+--------+---------------------+
6 rows in set (0.00 sec)

The following is the query to select last 6 months from the new table. The query is as follows −

mysql> select *from Newstable where NewsDatetime > date_sub(now(),Interval 6 month);

Output

+--------+---------------------+
| NewsId | NewsDatetime        |
+--------+---------------------+
|    102 | 2018-12-10 00:00:00 |
|    104 | 2018-12-12 00:00:00 |
|    106 | 2018-06-30 00:00:00 |
+--------+---------------------+
3 rows in set (0.00 sec)
raja
Published on 10-Jan-2019 11:16:36
Advertisements