- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to insert a row with a timestamp “X days ago” in MySQL?
To insert a row like this use the following syntax, wherein we are using CURRENT_TIMESTAMP −
insert into yourTableName values(CURRENT_TIMESTAMP - INTERVAL ABS(RAND() * 100) DAY);
To understand the above syntax, let us create a table −
mysql> create table DemoTable1983 ( DueDate timestamp ); Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1983 values(CURRENT_TIMESTAMP - INTERVAL ABS(RAND() * 100) DAY); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1983 values(CURRENT_TIMESTAMP - INTERVAL ABS(RAND() * 100) DAY); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1983 values(CURRENT_TIMESTAMP - INTERVAL ABS(RAND() * 100) DAY); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1983;
This will produce the following output −
+---------------------+ | DueDate | +---------------------+ | 2019-12-10 19:35:43 | | 2019-10-27 19:35:44 | | 2019-11-10 19:35:45 | +---------------------+ 3 rows in set (0.00 sec)
The current date time is as follows −
mysql> select now();
This will produce the following output −
+---------------------+ | now() | +---------------------+ | 2019-12-18 19:36:17 | +---------------------+ 1 row in set (0.00 sec)
Advertisements