UPDATE blogs SET start_date = '11/27/2012 00:00',end_date = '11/27/2012 00:00' WHERE id='9'
This query won't store start_date or end_date values for blog id 9 unless I set them to varchar type.
Tried with timestamp and date time but the query allways will return that 0 rows where affected
the thing is I need to be able to check for rows in a interval of time, and with varchar it makes very complicated.
What am i missing?
As stated in Date and Time Literals:
MySQL recognizes DATETIME and TIMESTAMP values in these formats:
As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012#12#31 11^30^45' are equivalent.
As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.
As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.
Therefore, the strings '11/27/2012 00:00' and '11/27/2012 00:00' are not valid MySQL datetime literals. You have two options (in some vague order of preference, without any further information of your requirements):
Provide your literals in a recognised format:
UPDATE blogs SET
start_date = '2012-11-27 00:00:00',
end_date = '2012-11-27 00:00:00'
WHERE id = 9
Use MySQL's STR_TO_DATE() function to convert the string:
UPDATE blogs SET
start_date = STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %H:%i'),
end_date = STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %H:%i')
WHERE id = 9
Try this:
UPDATE blogs
SET start_date = STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %h:%i:%s') --cast string to date in correct date format
,end_date = STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %h:%i:%s')--cast string to date in correct date format
WHERE id = 9 --removed quotes as this field's probably numeric
If using a timestamp column instead of datetime I think you need to do something like this:
UPDATE blogs
SET start_date = UNIX_TIMESTAMP(STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %h:%i:%s'))
,end_date = UNIX_TIMESTAMP(STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %h:%i:%s'))
WHERE id = 9
Related
The table I'm querying from has this DateTime column.
created_time
2022-03-19T15:21:52+08:00
2022-03-19T13:10:22+08:00
2022-03-19T13:09:52+08:00
2022-03-19T13:02:47+08:00
2022-03-20T20:51:03+08:00
select extract(year_month from curtime())
Using extract (as above) doesn't work as it will get me: 202203.
SELECT created_time
FROM `freemark-prod-zohocrm`.patients p
where select extract(year_month from curtime())
Therefore the query above will not give me any result as my 'where' clause needs to specifically ask for '2022-03%' and not 202203.
SELECT created_time
FROM `freemark-prod-zohocrm`.patients p
where date_format(p.created_time, '%Y')=(select extract(year from curtime()))
and date_format(p.created_time, '%m')=(select extract(month from curtime()))
Therefore I am currently using the query above to obtain Year='2022' AND Month='03' which I feel doesn't look that nice and might cause me future problems.
I am wondering if there is a more elegant way to get the current 'Year-Month' (eg.'2022-03%') to use in my 'where' clause.
Thank you for your time.
LIKE Example db<>fiddle
Since the query is a simple YYYY-MM prefixed lookup, use LIKE DATE_FORMAT(NOW(), '%Y-%m-%%') as 2022-03-%. Functioning the same for either DATETIME or VARCHAR column data-types, and is by-far the fastest solution regardless of indexing.
SELECT p.created_time
FROM `freemark-prod-zohocrm`.patients p
WHERE p.created_time LIKE DATE_FORMAT(NOW(), '%Y-%m-%%');
Compare YEAR_MONTH Criteria db<>fiddle
To fix the issue with the original query not returning results, match the criteria column and value functions. However, as a function is called on the column value a full-table scan will be performed.
SELECT p.created_time
FROM `freemark-prod-zohocrm`.patients p
WHERE EXTRACT(YEAR_MONTH FROM p.created_time) = EXTRACT(YEAR_MONTH FROM NOW());
To prevent a full-table scan avoid altering column values in the criteria using DATE_FORMAT(created_time), EXTRACT(... FROM created_time) or other functions, which will cause MySQL to check all rows in the table to determine if the condition matches.
MySQL 5.5 and earlier db<>fiddle
Note: In MySQL 5.5 and earlier, extract(year_month from curtime()) or for any date specific Temporal Intervals will return NULL because curtime() returns the TIME portion as HH:MM:SS.The behavior appears to have changed in MySQL 5.6 and later, where EXTRACT() will apply to the current date when the date argument is supplied as a TIME data-type and failing when supplied as a time string literal.
However, an undesirable value will be returned when using a date + time interval such as DAY_MINUTE and the date portion of the value is omitted.
SELECT
curtime(), /* 19:07:40 */
extract(year_month from curtime()), /* NULL */
extract(day_minute from curtime()); /* 1907 */
To resolve the issue always use NOW(), otherwise in MySQL 5.5 and earlier curtime() should be replaced with CURDATE() or NOW() depending on the interval being used.
DATE Interpreted Example db<>fiddle
As DATE_FORMAT() returns a string literal, to prevent string comparison issues in MySQL such as '10' > '2' = false, enforce a DATE or DATETIME context.
When using DATE or DATETIME interpreted values (see explanation below) to retrieve the rows for an entire month, the following criteria values can be used to force the condition to process in the context of a DATE data-type
DATE(DATE_FORMAT(NOW(), '%Y-%m-01')) to get the first day of the current month as a DATE data-type
LAST_DAY(NOW()) + INTERVAL 1 DAY to get the the first day of the next month as a DATE data-type.
SELECT p.created_time
FROM `freemark-prod-zohocrm`.patients p
WHERE p.created_time >= DATE(DATE_FORMAT(NOW() ,'%Y-%m-01'))
AND p.created_time < LAST_DAY(NOW()) + INTERVAL 1 DAY;
LAST_DAY(NOW()) will return the date as 2022-03-31
+ INTERVAL 1 DAY will increment the date by one day to 2022-04-01
MySQL 5.6+ Results
CREATE TABLE patients_varchar (
`id` INTEGER NOT NULL PRIMARY KEY,
`created_time` VARCHAR(25),
INDEX(`created_time`)
);
INSERT INTO patients_varchar
(`id`, `created_time`)
VALUES
('1', '2022-02-19T15:21:52+08:00'), /* Added to verify range */
('2', '2022-03-19T15:21:52+08:00'),
('3', '2022-03-19T13:10:22+08:00'),
('4', '2022-03-19T13:09:52+08:00'),
('5', '2022-03-19T13:02:47+08:00'),
('6', '2022-03-20T20:51:03+08:00'),
('7', '2022-03-31T20:51:03+08:00'),
('8', '2022-04-20T20:51:03+08:00'); /* Added to verify range */
created_time
2022-03-19T13:02:47+08:00
2022-03-19T13:09:52+08:00
2022-03-19T13:10:22+08:00
2022-03-19T15:21:52+08:00
2022-03-20T20:51:03+08:00
2022-03-31T20:51:03+08:00
VARCHAR and Date Time Literals Explanation
When the column data-type is VARCHAR using a valid date time string literal format such as YYYY-MM-DDTHH:MM:SS+08:00, MySQL will automatically interpret the column value format of YYYY-MM-DDTHH:MM:SS+MM:HH as a DATETIME data-type appropriately when provided a criteria value in the DATE or DATETIME data-type context.Please see the String and Numeric Literals in Date and Time Context for more details.
DATETIME context and time zone offsets
For MySQL 5.6+ to specify the inclusion of a time value, use TIMESTAMP(DATE_FORMAT(LAST_DAY(NOW()), '%Y-%m-%d 23:59:59')) to force a DATETIME context as opposed to using DATE().
For MySQL 5.5 and earlier db<>fiddle, when specifying a DATETIME context, the time zone offset in the column value is not parsed correctly and produces a different result. Using a string context of DATE_FORMAT(LAST_DAY(NOW()), '%Y-%m-%dT23:59:59') resolves the issue but may produce unexpected results, due to the string context comparison eg: '10' > '2' = false.
Note: the T is required for MySQL to parse the YYYY-MM-DDTHH:MM:SS formatted column value correctly.
For example the following conditions will all return true due to the DATETIME context. While MySQL 8.0+ will process the time zone offset when it is included in the string.
SELECT
'2022-02-19T15:21:52+08:00' = TIMESTAMP('2022-02-19T15:21:52'),
'2022-02-19T15:21:52+08:00' < TIMESTAMP('2022-02-20T15:21:52'),
'2022-02-19T15:21:52+08:00' > TIMESTAMP('2022-02-18T15:21:52'),
'2022-02-19T00:00:00+08:00' = TIMESTAMP('2022-02-19'),
'2022-02-19T15:21:52+08:00' < TIMESTAMP('2022-02-20'),
'2022-02-19T15:21:52+08:00' > TIMESTAMP('2022-02-18');
As opposed to the following conditions comparing strings that all return unexpected results.
SELECT
'2022-02-19T15:21:52+08:00' = '2022-02-19T15:21:52', # false
'2022-02-19T15:21:52+08:00' <= '2022-02-19T15:21:52', # false
'2022-02-19T15:21:52+08:00' > '2022-02-19T15:21:52'; # true
querying based on function calls such as extract(), or others datepart(), etc. are not Sargeable
What you would be better doing is something like
where
created_time >= '2022-03-01'
AND created_time < '2022-04-01'
This way, it gets the entire month in question including time portion up to 2022-03-31 # 11:59:59pm.
Now, to compare automatically against whatever the current date IS, you can do with MySQL Variables to compute the first of the month and beginning of next month for your from/to range.
select
...
from
( select #FirstOfMonth := DATE_FORMAT(CURDATE(), '%Y-%m-01'),
#FirstOfNextMonth := date_add( #FirstOfMonth, interval 1 month )) sqlvars,
`freemark-prod-zohocrm`.patients p
where
p.created_time >= #FirstOfMonth
AND p.created_time < #FirstOfNextMonth
I have a datetime datatype in my table,
`DateAdded` datetime(4) DEFAULT NULL,
I have a record in my database with DateAdded = 2017-09-11 17:02:48.6531 value, ( it's ID = 16452994 ).
When I want to get it with following query return NULL
select `ID`,`DateAdded` from `Add` where `DateAdded` <= FROM_UNIXTIME(('1505071799' +86400 ), '%Y-%m-%d %h:%i:%s') and ID =16452994 ;
FYI : FROM_UNIXTIME(('1505071799' +86400 ), '%Y-%m-%d %h:%i:%s') = 2017-09-11 23:59:59
It's strange that 2017-09-11 17:02:48.6531 <= 2017-09-11 23:59:59 return false
but when I try the following query I'll get my desire result.
select `ID`,`DateAdded` from `Add` where `DateAdded` <= FROM_UNIXTIME(('1505071799' +86400 +1 ), '%Y-%m-%d %h:%i:%s') and ID =1645299;
I want to know why this is happening and how can I resolve this problem?
FROM_UNIXTIME(unix_timestamp), FROM_UNIXTIME(unix_timestamp,format)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone. unix_timestamp is an internal timestamp value such as is produced by the UNIX_TIMESTAMP() function.
If format is given, the result is formatted according to the format string, which is used the same way as listed in the entry for the DATE_FORMAT() function.
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime
I have one field startTime in my database and the value is '7:00:00 PM', I want to add 20 minutes in this time and store this in a new field as endtime. I want endtime in same format as is startTime that is '07:20:00 PM', I used ADDTIME, and many more function to do this, but unable to get the format of AM/PM, I used
DATE_ADD('NEXT_CONTACT_TIME', INTERVAL 20 MINUTE), DATE_FORMAT(ADDTIME(NEXT_CONTACT_TIME,'00:20:00'),'%h:%i:%s %p') as endTime
But, I'm not able to get AM/Pm
Use This
DECLARE #StartTime TIME(0) = '07:00:00 AM'; --Time
DECLARE #MinutesToAdd INT = 20; --Added 20 Minutes
SELECT SUBSTRING((CONVERT(VARCHAR(8), DATEADD(MINUTE, #MinutesToAdd, #StartTime), 109)),0,8) + ' ' + RIGHT(CONVERT(VARCHAR(30), DATEADD(MINUTE, #MinutesToAdd, #StartTime), 9), 2) as Time
As per my knowledge mysql default time format is 24HR that means there is no am/pm you should manage the time when fetching or after fetching the data.
A date and time combination. The supported range is '1000-01-01
00:00:00' to '9999-12-31 23:59:59'. MySQL displays DATETIME values in
'YYYY-MM-DD HH:MM:SS' format, but permits assignment of values to
DATETIME columns using either strings or numbers.
Refer this
I have this query
SELECT * FROM tracklogs.sms_outbound
WHERE gsmno = 'rk4#*******.com.ph'
AND cdate > cast('2013/11/14 09:44:48 PM' as datetime)
where cdate format is in %Y-%m-%d %h:%i:%s %p.
I have tried converting the date into that format then cast it as datetime but still doesn't working.
Use STR_TO_DATE() to correctly convert the datetime literal you have provided to a proper DATETIME value. It seems that your cdate column is a char() or varchar() column. So you will also need to convert that to DATETIME to compare it.
What you need is this:
That works like this (http://sqlfiddle.com/#!2/d41d8/48741/0)
STR_TO_DATE(cdate, '%Y-%m-%d %h:%i:%s %p') >
STR_TO_DATE('2013/11/14 09:44:48 PM', '%Y/%m/%d %h:%i:%s %p')
Converting these strings to DATETIME data items ensures that the comparison handles both the date and the time correctly. See this fiddle (http://sqlfiddle.com/#!2/d41d8/48743/0)
But, you should consider changing your cdate item to a DATETIME, because then you'll be able to index it and speed up your search.
SELECT * FROM tracklogs.sms_outbound
WHERE gsmno = 'rk4#*******.com.ph'
AND UNIX_TIMESTAMP(str_to_date(cdate,'%Y-%m-%d %H:%i:%s')) > UNIX_TIMESTAMP('2013-11-14 09:44:48')
I'm trying to create a query using mysql.
select ID,NCOde,ifnull(EndTime,now())-starttime from xxx where starttime between
'2012-05-09 00:00:00' and '2012-05-09 23:59:59'
the problem is ifnull(EndTime,now()) return datetime in 24 hours format, while the starttime using am/pm format.
I've tried using DATE_FORMAT(starttime, '%m-%d-%Y %T'), but it seems that the operation changed the datetime type to other type.
Any advice?
Use STR_TO_DATE() to convert your starttime string to a MySQL DATETIME:
STR_TO_DATE(starttime, '%m-%d-%Y %r')
and then use TIMEDIFF() to subtract two times:
select ID,NCOde,
TIMEDIFF(ifnull(EndTime,now()), STR_TO_DATE(starttime, '%m-%d-%Y %r'))
from xxx
where STR_TO_DATE(starttime,'%m-%d-%Y %r')
between '2012-05-09 00:00:00' and '2012-05-09 23:59:59'
You should probably consider changing the data type of the starttime column to DATETIME or TIMESTAMP. Note also that this assumes EndTime is already of such a data type, or else you will also have to perform a similar conversion with it too.
Use the DATE_SUB() function.
Plus what eggyal said.