patternsqlMinor
Default value for "microtime" column in MySQL
Viewed 0 times
columnvaluedefaultmysqlformicrotime
Problem
My interest is to store the time with FSP of 6. As I've read, this cannot be achieved with
Is there anyway I can set (or even write some code to create) a default value for such a field?
I want to use something like
TIMESTAMP or DATETIME data types. So, I have a double field to store the output of the microtime function.Is there anyway I can set (or even write some code to create) a default value for such a field?
I want to use something like
NOW(6) and get 1442059062.065123 for example.Solution
You could format it with
You can find any others date and time functions here. You could add a
Example:
UNIX_TIMESTAMP like below:mysql> SELECT UNIX_TIMESTAMP(NOW(6));
+------------------------+
| UNIX_TIMESTAMP(NOW(6)) |
+------------------------+
| 1442068528.543100 |
+------------------------+
1 row in set (0,00 sec)
mysql>You can find any others date and time functions here. You could add a
trigger and if you want a default value for your decimal(16, 6) microtime, use BEFORE INSERT and replace your NEW.bigintvalue=UNIX_TIMESTAMP(NOW(6));.Example:
mysql> CREATE TABLE `test`.`test1` (
-> `id` INT NOT NULL AUTO_INCREMENT,
-> `time` DECIMAL(16, 6) NULL,
-> PRIMARY KEY (`id`));
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> DELIMITER //
mysql> CREATE DEFINER=`root`@`localhost` TRIGGER `test`.`test1_BEFORE_INSERT` BEFORE INSERT ON `test1` FOR EACH ROW
-> BEGIN
-> SET NEW.time=UNIX_TIMESTAMP(NOW(6));
-> END
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql>
mysql> # Adding 1 into id field
mysql> INSERT INTO `test`.`test1` (`id`) VALUES ('1');
Query OK, 1 row affected (0.00 sec)
mysql> select * from test.test1;
+----+-------------------+
| id | time |
+----+-------------------+
| 1 | 1442069359.675330 |
+----+-------------------+
1 row in set (0.00 sec)
mysql>Code Snippets
mysql> SELECT UNIX_TIMESTAMP(NOW(6));
+------------------------+
| UNIX_TIMESTAMP(NOW(6)) |
+------------------------+
| 1442068528.543100 |
+------------------------+
1 row in set (0,00 sec)
mysql>mysql> CREATE TABLE `test`.`test1` (
-> `id` INT NOT NULL AUTO_INCREMENT,
-> `time` DECIMAL(16, 6) NULL,
-> PRIMARY KEY (`id`));
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> DELIMITER //
mysql> CREATE DEFINER=`root`@`localhost` TRIGGER `test`.`test1_BEFORE_INSERT` BEFORE INSERT ON `test1` FOR EACH ROW
-> BEGIN
-> SET NEW.time=UNIX_TIMESTAMP(NOW(6));
-> END
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql>
mysql> # Adding 1 into id field
mysql> INSERT INTO `test`.`test1` (`id`) VALUES ('1');
Query OK, 1 row affected (0.00 sec)
mysql> select * from test.test1;
+----+-------------------+
| id | time |
+----+-------------------+
| 1 | 1442069359.675330 |
+----+-------------------+
1 row in set (0.00 sec)
mysql>Context
StackExchange Database Administrators Q#114850, answer score: 6
Revisions (0)
No revisions yet.