This statement works fine:
SELECT * FROM table_name
WHERE DATE(date_event) < DATE(NOW() - INTERVAL 90 DAY);
Using the same WHERE clause in DELETE statement does not works :
DELETE FROM table_name
WHERE DATE(date_event) < DATE(NOW() - INTERVAL 90 DAY);
Return message :
Error Code: 1292. Truncated incorrect datetime value: '2018-01-10T13:22:29.000000Z'
Datatype of field "date_event" is CHAR(27).
Testing DATE() function with next SQL statement works fine :
SELECT DATE('2018-01-10T13:22:28.000000Z');
'2018-01-10'
Here the complete SQL code :
CREATE TABLE `table_name` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date_event` char(27) NOT NULL COMMENT 'YYYY-MM-DDThh:mm:ss.ffffffZ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='Test';
INSERT INTO table_name
(date_event) VALUES ('2018-01-10T13:22:28.000000Z');
SELECT * FROM table_name
WHERE DATE(date_event) < DATE(NOW() - INTERVAL 90 DAY);
DELETE FROM table_name
WHERE DATE(date_event) < DATE(NOW() - INTERVAL 90 DAY);
date_event field is Char (string type). We will need to convert it to MySQL datetime format using Str_to_Date() function:
'2018-01-10T13:22:28.000000Z' can basically be written in terms of format specifiers as: '%Y-%m-%dT%T.%fZ'.
So, your Delete query should be as follows (DB Fiddle DEMO):
DELETE FROM table_name
WHERE STR_TO_DATE(date_event, '%Y-%m-%dT%T.%fZ') < DATE(NOW() - INTERVAL 90 DAY);
And, your Select query should be:
SELECT * FROM table_name
WHERE STR_TO_DATE(date_event, '%Y-%m-%dT%T.%fZ') < DATE(NOW() - INTERVAL 90 DAY);
Additional Details:
%Y Year as a numeric, 4-digit value
%m Month name as a numeric value (00 to 12)
%d Day of the month as a numeric value (01 to 31)
%T Time in 24 hour format (hh:mm:ss)
%f Microseconds (000000 to 999999)
Complete list of format specifiers can be seen at: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format
Related
tring to use date filter for same date the date stored in datebase for column MODIFIED_DATE is '2021-03-18 14:34:34' format
The where clause condition for filter is "where (MODIFIED_DATE BETWEEN '2021-03-18 00:00:00' AND '2021-03-18 00:00:00')" but it is unable to fetch the records
example query:
select MODIFIED_DATE
from instance_history where (MODIFIED_DATE BETWEEN '2021-03-18 00:00:00' AND '2021-03-18 00:00:00') ;
it is showing record not found
i have used this method but it does not helped cast(cast(left(PIH.PROCESS_MODIFIED_DATE, 10) as date) as datetime) as PROCESS_MODIFIED_DATE but it does not worked
See below sample
select current_timestamp, date_format(current_timestamp(), "%Y-%m-%d 00:00:00") 'ExpectedDate format';
current_timestamp | ExpectedDate format
2022-07-29 17:12:19 | 2022-07-29 00:00:00
Replace current_timestamp() with Modified_Date
Do not use BETWEEN. Use 2 separate conditions (#date is needed value, for example, '2021-03-18'):
SELECT modified_date
FROM instance_history
WHERE modified_date >= #date
AND modified_date < #date + INTERVAL 1 DAY) ;
When date literal is used then the timepart is '00:00:00'.
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));
I have a database column called time
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
But when I run the following query using PDO:
DELETE FROM `table` WHERE time < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL :days DAY))
It throws the following exception:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1555980012' for column 'time' at row 1
I don't understand why this is happening, could any one please explain?
You do not need to use UNIX_TIMESTAMP function in your where clause to convert date to number.
This should work with no issue:
DELETE FROM `table` WHERE `time` < DATE_SUB(NOW(), INTERVAL :days DAY)
I have a column (lastlogin) that contains the following value = '17th May 2017 09:40:43 AM' ----
php function to create stamp:
date('jS F Y h:i:s A');
How can I do a select query that shows the (lastlogin) in that last 30 minutes from current time?
I'm guessing we have to convert date/time to string and separate the 2?
Any help would be amazing.
UPDATE:
I've tried the following but did not work returned more aless of records in table:
SELECT user_id, ('lastlogin' >= DATE_FORMAT(NOW() - INTERVAL 30 MINUTE,'%D %M %Y %H:%m:%s %p')) as result
FROM login_last
where lastlogin >= DATE_FORMAT(NOW() - INTERVAL 30 MINUTE,'%D %M %Y %H:%m:%s %p')
GROUP BY user_id
TABLE Structure
[id] int(8)
[user_id] int(11)
[lastlogin] varchar(30)
[browser] varchar(300)
You will need to convert your string date to a datetime format for the comparison, then compare the current datetime to the value stored.
You could also convert them to sortable strings for comparison. Something like "2017-05-17 10:20:10 AM", but it's easier to compare using the datetime type.
Reference:
str_to_date
date_format
MySQL Query:
SELECT
`user_id`,
`last_login`,
(STR_TO_DATE(`lastlogin`,'%D %b %Y %h:%i:%s %p') >= (NOW() - (INTERVAL 30 MINUTE))) as `in_range`
FROM `login_last`
WHERE (STR_TO_DATE(`lastlogin`,'%D %b %Y %h:%i:%s %p') >= (NOW() - (INTERVAL 30 MINUTE)))
SELECT * FROM tablename WHERE lastlogin >= DATE_SUB(NOW(), INTERVAL 30 MINUTE);
The challenge is to convert the result of DATE_SUB(NOW(), INTERVAL 30 MINUTE) to the correct format '17th May 2017 09:40:43 AM' (or format the left condition alias your lastLogin to UNIX_TIMESTAMP / datetime). In case you are inserting the date values yourself you probably already know how to get that format and can complete that yourself. Otherwise I recommend you to create a new question which is about formatting UNIX_TIMESTAMPs to your desired format.
A blind guess without having the chance to try that on my on would be:
SELECT * FROM tablename
WHERE UNIX_TIMESTAMP(lastlogin) >= DATE_SUB(NOW(), INTERVAL 30 MINUTE);
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...