Languages
[Edit]
EN

MySQL - set current DATETIME as default

3 points
Created by:
Veer-Ahmad
487

In this article, we would like to show you how to set current DATETIME as default value in DATETIME column in MySQL.

Quick solution:

CREATE TABLE `table_name` (
	`column_name` DATETIME DEFAULT CURRENT_TIMESTAMP
);

 

Practical example

In this example, we will create users table with registration_time column which default value will be the current timestamp.

Query:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`username` VARCHAR(50) NOT NULL,
	`registration_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
	PRIMARY KEY (`id`)
);

Now when we insert some values to the table and don't specify the registration_time value, the column will be filled with current timestamp value.

Query:

INSERT INTO `users`
	(`username`)
VALUES
	('Tom'),
	('Chris'),
	('Jack'),
    ('Kim'),
    ('Marco'),
	('Kate'),
	('Nam');

Result:

MySQL - set current DATETIME as default - result
MySQL - set current DATETIME as default - result

Alternative titles

  1. MySQL - set default value for DATETIME column
  2. MySQL - use current time as default value for DATETIME column
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MySQL - dates

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join