insert current date time mysql

How to Insert Current Date Time in MySQL

MySQL supports a wide range of data types. Sometimes you may need to insert current date time in MySQL column. In this article, we will learn how to do this using system functions instead of using literal strings.

How to Insert Current Date Time in MySQL

Let us say you have the following MySQL table sales (id, product, amount, created_at).

mysql> create table sales(id int, product varchar(10), amount int, created_at datetime);

Typically, people use literal strings to enter current date or date time in MySQL as shown below.

mysql> insert into sales(id, product, amount, created_at) values(1, 'ABC', 180, '2022-11-22');

mysql> insert into sales(id, product, amount, created_at) values(2, 'ABC', 100, '2022-11-22 10:30:00');

The above methods can be tedious, error prone and inaccurate. Instead you can also use system function curdate() to insert current date value, and now() function to insert current date time value in MySQL.

mysql> insert into sales(id, product, amount, created_at) values(3, 'ABC', 280, curdate());

mysql> insert into sales(id, product, amount, created_at) values(4, 'ABC', 150, now());

mysql> select * from sales;
+------+---------+--------+---------------------+
| id   | product | amount | created_at          |
+------+---------+--------+---------------------+
|    1 | ABC     |    180 | 2022-11-22 00:00:00 |
|    2 | ABC     |    100 | 2022-11-22 10:30:00 |
|    3 | ABC     |    280 | 2022-11-22 00:00:00 |
|    4 | ABC     |    150 | 2022-11-22 11:14:28 |
+------+---------+--------+---------------------+

Please note, if you enter current date into a datetime column then it will set the time to 00:00:00 as shown above.

In this article, we have learnt how to insert current date time in MySQL.

Also read:

How to Uninstall MySQL Completely in Ubuntu
How to View MySQL Query Locking Table
How to Group By Date on Datetime Column
How to Select By String Length in MySQL
How to Remove All Tables in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *