You can use date-sub() and now() function from MySQL to fetch the rows added in last hour.
Syntax
The syntax is as follows −
select *from yourTableName where yourDateTimeColumnName <=date_sub(now(),interval 1 hour);
The above query gives the result added last hour. To understand the above concept, let us first create a table. The query to create a table is as follows −
mysql> create table LastHourRecords -> ( -> Id int, -> Name varchar(100), -> Login datetime -> ); Query OK, 0 rows affected (0.67 sec)
Insert records in the form of datetime using insert command. The query to insert record is as follows −
mysql> insert into LastHourRecords values(1,'John',' 2018-12-19 10:00:00'); Query OK, 1 row affected (0.17 sec) mysql> insert into LastHourRecords values(2,'Carol','2018-12-19 10:10:00'); Query OK, 1 row affected (0.15 sec) mysql> insert into LastHourRecords values(3,'Sam','2018-12-19 10:05:00'); Query OK, 1 row affected (0.13 sec) mysql> insert into LastHourRecords values(4,'Mike','2018-12-18 12:10:00'); Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from LastHourRecords;
Output
+------+-------+---------------------+ | Id | Name | Login | +------+-------+---------------------+ | 1 | John | 2018-12-19 10:00:00 | | 2 | Carol | 2018-12-19 10:10:00 | | 3 | Sam | 2018-12-19 10:05:00 | | 4 | Mike | 2018-12-18 12:10:00 | +------+-------+---------------------+ 4 rows in set (0.00 sec)
Let us see the query to fetch rows added in the last hour −
mysql> select *from LastHourRecords -> where Login <=Date_sub(now(),interval 1 hour);
Output
+------+-------+---------------------+ | Id | Name | Login | +------+-------+---------------------+ | 1 | John | 2018-12-19 10:00:00 | | 2 | Carol | 2018-12-19 10:10:00 | | 3 | Sam | 2018-12-19 10:05:00 | +------+-------+---------------------+ 3 rows in set (0.00 sec)