Create table and set default value to NOW() + 24 hours - mysql

I'm trying to create a table and set the default value to now() + 24 hours. I'm getting syntax errors when trying to do this.
This doesn't work
CREATE TABLE IF NOT EXISTS `my_table` (
`my_table_id` CHAR(36) BINARY NOT NULL ,
`expiration_time` DATETIME NOT NULL DEFAULT (NOW() + INTERVAL 24 HOUR),
PRIMARY KEY (`my_table_id`)
) ENGINE=InnoDB;
Although this does work SELECT NOW() + INTERVAL 24 HOUR; so i'm not sure why it doesn't work when trying to create a table.

Expressions for defaults are not supported in MySQL 5.7.
You can implement a "default" expression in a trigger such as the following:
CREATE TRIGGER my_awesome_trigger BEFORE INSERT ON my_table
FOR EACH ROW
SET NEW.expiration_time = COALESCE(NEW.expiration_time, NOW() + INTERVAL 24 HOUR));

Related

How to set DEFAULT ON UPDATE CURRENT_TIMESTAMP + 5 MINUTES?

I have a table with three columns:
"code" column (integers)
two DATETIME columns ("created_at", "expires_at")
"created_at" column default value is CURRENT_TIMESTAMP.
"expires_at" column default value is CURRENT_TIMESTAMP + INTERVAL 5 MINUTE.
So far no problem.
Now I would like the ON UPDATE values to be the same as the default ones:
for the "created_at" column, ON UPDATE CURRENT_TIMESTAMP works like a charm.
for the "expires_at" column, I can't get ON UPDATE (CURRENT_TIMESTAMP + INTERVAL 5 MINUTE)
The query to create the "expires_at" column
ALTER TABLE codes ADD expires_at DATETIME DEFAULT (CURRENT_TIMESTAMP + INTERVAL 5 MINUTE);
work successfully.
When I try to add ON UPDATE,
ALTER TABLE codes ADD expires_at DATETIME DEFAULT (CURRENT_TIMESTAMP + INTERVAL 5 MINUTE) ON UPDATE (CURRENT_TIMESTAMP + INTERVAL 5 MINUTE);
this query doesn't work.
It returns the error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(CURRENT_TIMESTAMP + INTERVAL 5 MINUTE)' at line 1
I also tried with:
NOW() instead of CURRENT_TIMESTAMP
DATE_ADD() and ADDTIME() functions
but these solutions also do not work.
Such expression in ON UPDATE is not allowed. You may use intermediate updated_at column and generated expired_at column.
DEMO
CREATE TABLE test (
id INT PRIMARY KEY,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP,
expired_at DATETIME GENERATED ALWAYS AS (updated_at + INTERVAL 3 MINUTE)
);
INSERT INTO test (id) VALUES (1);
SELECT *, SLEEP(2) FROM test;
id
created_at
updated_at
expired_at
SLEEP(2)
1
2023-01-06 14:00:35
2023-01-06 14:00:35
2023-01-06 14:03:35
0
UPDATE test SET id = 2 WHERE id = 1;
SELECT * FROM test;
id
created_at
updated_at
expired_at
2
2023-01-06 14:00:35
2023-01-06 14:00:37
2023-01-06 14:03:37
fiddle

Automatically update columns values after 6 days

I created a new table in MySQL, I want to make changes in ( column1 and column2 ) columns values automatically in sql.
I tried this code, but their is no changes in table after 6 days.
CREATE EVENT weekly
ON SCHEDULE
EVERY 6 days
STARTS DATE(NOW()) + INTERVAL (6 DAYS(NOW())+1) DAY
ON COMPLETION PRESERVE
DO
UPDATE INTO `MyTable` (`value1`, `value2`)
SELECT `column1` , `column2`)
WHERE `column1` >= NOW() - INTERVAL 6*24 HOUR;
Your UPDATE statement is not correct. It should be like below -
UPDATE `MyTable`
SET `column1` = ???
,`column2` = ???
WHERE `column1` >= NOW() - INTERVAL 6*24 HOUR;
Replace ??? with the the value you want to update in col1 and col2
Not sure how you want to update the value for column1 and 2. But the event should look like this:
DELIMITER //
CREATE EVENT IF NOT EXISTS daily_update
ON SCHEDULE
EVERY 1 DAY STARTS DATE(NOW())
ON COMPLETION PRESERVE
COMMENT 'Update myTable after 6 days'
DO
BEGIN
UPDATE MyTable
SET column1='value1',
column2='value2'
WHERE column1>= (NOW() - INTERVAL 6*24 HOUR);
END
//

What's wrong with this simple MySQL syntax? Summing the dates

Among the rest, I've got three columns in my table:
start- timestamp, the default value is CURRENT_TIMESTAMP
duration- datetime, usually 0000-00-07 00:00:00 (one week)
end - timestamp, the default value is 0000-00-00 00:00:00
Here's what I do:
UPDATE `banners` SET `end` = `start` + `duration` WHERE `id` = 93
No errors appear, the id is exact - but the operation doesn't execute, the end field just remains at zeros.
What's wrong? Any quotes, brackets needed? I also tried making the middle field the timestamp type as well with no result.
Very possible, just a little ugly in terms of code...
UPDATE `banners`
SET `end` = FROM_UNIXTIME(UNIX_TIMESTAMP(`start`) + (UNIX_TIMESTAMP(`duration`) - UNIX_TIMESTAMP('1970-01-01 00:00:00')),'%Y-%d-%m %h:%i')
WHERE `id` = 93
...you just need to convert everything to seconds, add the duration from teh second one and then convert back to a datetime string for setting :)
You cannot add DATETIME values the same way you add numbers. What's the meaning of April 25, 2016 added to January 5, 2016?
You should store your durations using the smallest time unit that can be used to represent them as integer numbers and use the MySQL DATE_ADD() function instead of the addition.
For example, if duration is 1 WEEK then you can use any of:
UPDATE `banners` SET `end` = DATE_ADD(`start`, INTERVAL 1 WEEK) WHERE `id` = 93
UPDATE `banners` SET `end` = DATE_ADD(`start`, INTERVAL 7 DAY) WHERE `id` = 93
UPDATE `banners` SET `end` = DATE_ADD(`start`, INTERVAL 168 HOUR) WHERE `id` = 93
If duration is usually 1 week, you can use DATE_ADD() function of MySql
DATE_ADD(start,INTERVAL 7 DAY)
Hope that helps

Sql date comparison in where clause is not working as expected

I'm facing a strange mysql behavior...
If I want to return the rows from "MyTable" with a date lower than date-10 seconds ago or a future date
I also store future date because in my real program, I "launch" some queries with delay and date is actually the last query date...i.e.: a kind of queue...:
SELECT (NOW() - date) AS new_delay, id
FROM MyTable
WHERE (NOW() - date < 10)
ORDER BY new_delay DESC;
This one does not work as expected: It returns all the entries:
EDIT: here is the result:
However, this one is working just fine:
SELECT (NOW() - date) AS new_delay, id
FROM MyTable
WHERE (NOW() < date + 10)
ORDER BY new_delay DESC;
DB example:
CREATE TABLE IF NOT EXISTS `MyTable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
INSERT INTO `MyTable` (`id`, `date`) VALUES
(1, (NOW())),
(2, (NOW()-10)),
(3, (NOW()+100));
Any ideas??
Don't do the comparisons like that. In a numeric context now() end up being converted to an integer -- and in an arcane format. Instead, use DATEDIFF() or just regular comparisons. For instance, if you want the difference in days:
SELECT datediff(curdate(), date) as new_delay, id
FROM MyTable
WHERE date >= date_sub(now(), interval 10 day)
ORDER BY new_delay DESC;
use mysql DATEDIFF
select DATEDIFF(curdate(),date) as new_delay, id from MyTable
where date >= date_sub(curdate(), interval 10 day)
ORDER BY new_delay DESC;
DATEDIFF() function returns the time between two dates
As proposed by #Gordon in the his answer, I can use the date_sub / date_add functions...
I can correct the where clause to be :
WHERE NOW() < date_add(ServerRequests.date, interval 10 second)
OR
WHERE date > date_sub(now(), interval 10 second)
OR as proposed in my initial post:
WHERE (NOW() < date + 10)
But I still don't see why I cannot use the sub operation...So if anyone can give me a reason, I would be happy to understand...

MySQL date interval on select

i've made this SQL code :
CREATE TABLE `logs` (
`id_log` INT(11) NOT NULL AUTO_INCREMENT,
`data_log` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id_log`),
)
i made it to Insert a record when my server goes down,but i would like to make some check if it wasn't Inserted the same record 10 minutes before.
So i was looking for some SELECT that shows only records from NOW() to 10 minutes before.
You're looking for INTERVAL # [UNIT], there's various ways to use it -- http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html:
SELECT count(*)
FROM logs
WHERE data_log > NOW() - INTERVAL 10 MINUTE;
This will return the count of records written to the log in the last ten minutes:
SELECT Count(*) as count_in_last_10 FROM logs WHERE data_log BETWEEN DATE(NOW()-INTERVAL 10 MINUTE) AND NOW()