How to select all records that are 10 minutes within current timestamp in MySQL?

MySQLMySQLi Database

You can select all records that are 10 minutes within current timestamp using the following syntax−

SELECT *FROM yourTableName
WHERE yourColumnName > = DATE_SUB(NOW(),INTERVAL 10 MINUTE);

To understand the above syntax, let us create a table. The query to create a table is as follows−

mysql> create table users
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserName varchar(20),
   -> UserLastseen datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.91 sec)

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

mysql> insert into users(UserName,UserLastseen) values('Larry','2019-01-15 02−45−00');
Query OK, 1 row affected (0.15 sec)

mysql> insert into users(UserName,UserLastseen) values('Sam',now());
Query OK, 1 row affected (0.25 sec)

mysql> insert into users(UserName,UserLastseen) values('Mike','2019-01-15 02−30−00');
Query OK, 1 row affected (0.15 sec)

mysql> insert into users(UserName,UserLastseen) values('Bob','2019-01-15 15−02−00');
Query OK, 1 row affected (0.23 sec)

mysql> insert into users(UserName,UserLastseen) values('David','2019-01-15 14−55−00');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from users;

The following is the output−

+----+----------+---------------------+
| Id | UserName | UserLastseen        |
+----+----------+---------------------+
|  1 | Larry    | 2019-01-15 02−45−00 |
|  2 | Sam | 2019-01-15 15−01−52 |
|  3 | Mike | 2019-01-15 02−30−00 |
|  4 | Bob | 2019-01-15 15−02−00 |
|  5 | David | 2019-01-15 14−55−00 |
+----+----------+---------------------+
5 rows in set (0.00 sec)

Here is the query to select all records that are 10 minutes within the current timestamp−

mysql> select *from users
   -> where UserLastseen> = date_sub(now(),interval 10 minute);

The following is the output−

+----+----------+---------------------+
| Id | UserName | UserLastseen        |
+----+----------+---------------------+
|  2 | Sam      | 2019-01-15 15−01−52 |
|  4 | Bob      | 2019-01-15 15−02−00 |
|  5 | David    | 2019-01-15 14−55−00 |
+----+----------+---------------------+
3 rows in set (0.00 sec)
raja
Published on 01-Feb-2019 16:58:44
Advertisements