SQL Where clause with VARCHAR date - mysql

I have a MySQL DB to work with which has a LASTUPDATE column as VARCHAR.
This field has this format: YYYY-MM-DD HH:mm:ss
I need to set up a SELECT query to find all rows after e certain date, so i was trying to use the CONVERT function in this way
SELECT * from POWER WHERE CONVERT(DATETIME, LASTUPDATE) > 'CONVERT(DATETIME, '2016-12-29 17:24:22')'
but i'm getting the error
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 'LASTUPDATE) > 'CONVERT(DATETIME, '2016-12-29 17:32:52')'' at line 1
I have also tried to use:
SELECT * from POWER WHERE CONVERT(DATETIME, LASTUPDATE) > '2016-12-29 17:32:52' but i'm getting the same error

You could use the str_to_date
SELECT *
from POWER
WHERE str_to_date(LASTUPDATE, '%Y-%m-%d %H:%i:%s' ) >
str_to_date('2016-12-29 17:24:22', '%Y-%m-%d %H:%i:%s' )

Use str_to_date()
The query should use str_to_date() like this. See MySQL Manual for more details
SELECT
*
from POWER
WHERE
str_to_date(LASTUPDATE, '%Y-%m-%d %H:%i:%s') > '2016-12-29 17:24:22'
Date and time literial
Note that MySQL accepts date and time literals, so you do not need another str_to_date on the right-hand side of the > operator. See this for more details.
About the form between ... and ... on a string field storing date value
Some suggested using the form of between ... and ..., such as the one
shown below. Note that this method would work only if the string
values happen to use a format in which sorting the string alphabetically (in the given collation) happens to give the same sorting order as date (the format used in the original question -- '%Y-%m-%d %H:%i:%s' -- happens to satisfy this condition, but this is not guaranteed (see an example below) for many string representations of date/time values).
SELECT
*
from POWER
WHERE
LASTUPDATE between '2016-12-29 17:24:22' AND '2016-12-31 23:59:59';
And it would fail if the string values are using a different format, such as these:
create table power (
lastupdate varchar(40) not null default ''
) engine=innoDB;
insert into power
values
('Dec 30, 2016 07:24:22')
, ('Jan 28, 2016 07:24:22')
For the above, we must still use the str_to_date() function (this time with a format argument %b %d, %Y %H:%i:%s that is matching the format used with the string values)
SELECT
*
from POWER
WHERE
str_to_date(LASTUPDATE, '%b %d, %Y %H:%i:%s') > '2016-12-29 17:24:22';
I have an sqlfiddle.com page showing the above example.

convert is an MS-SQL Server function. In MySQL, you can use the str_to_date function with similar semantics:
SELECT *
FROM power
WHERE STR_TO_DATE(lastupdate, '%Y-%m-%d %H-%i-%s') >
STR_TO_DATE('2016-12-29 17:24:22', '%Y-%m-%d %H-%i-%s')

Related

Covert varchar(150) to datetime in sql workbench

I have a column with values '2015-02-14 12:23 AM' declared as varchar(150), I tried using to_date, convert and cast but not able to change the format. I would need this to filter on specific month/year/day. Thanks for the help
PS: Mysql instance is running on RDS through amazon AWS - not sure if its relevant
I suggest storing dates on proper date data type.
to_date is an Oracle function.
In MySQL, you can use STR_TO_DATE to converts a string to date then use Date_format to give the format you need
SELECT DATE_FORMAT(STR_TO_DATE(dt,'%Y-%m-%d %h:%i %p'),'%m/%Y/%d')
from test;
Demo
You can use substring with concat without the need of converting to date format:
select concat(substring(dt,6,2),'/', substring(dt,1,4),'/',substring(dt,9,2)) as my_date
from test;
Demo
SELECT CAST( SUBSTRING_INDEX( '2015-02-14 12:23 AM',
' ',
2
)
AS DATETIME
)
returns the datetime value. If you need to use this value in datetime context then you may remove CAST, it will be performed implicitly:
SELECT TIMESTAMPDIFF ( MINUTE,
SUBSTRING_INDEX( '2015-02-14 12:23 AM',
' ',
2
),
'2015-02-14 12:34'
)

Using STR_TO_DATE with insert

I have a test table in my database with the following structure: id(PK, Auto_Increment), dataI(datetime), dataF (datetime).
Using MySQL Workbench, when I try to insert a record I am having problems. I tried different ways using str_to_date to fix it.
INSERT INTO test(dataI, dataF)
VALUES(STR_TO_DATE('2020-01-10 18:00:00', '%YYYY-%MM-%DD hh:mm:ss'), STR_TO_DATE('2020-01-10 24:00:00', '%YYYY-%MM-%DD hh:mm:ss'))
Error code 1411: Incorrect datetime value for function str_to_date
'24:00:00' is not a valid time component for a DATETIME literal.
The format specification must match the string. The list of valid specifiers is documented under the DATE_FORMAT function, which is referenced under the documentation for the STR_TO_DATE function on the same page.
Reference:
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format
Format of that first value could be specified as '%Y-%m-%d %h %H:%i:%s'
or more concisely as '%Y-%m-%d %T'
We don't need to use STR_TO_DATE function when date literals are supplied in the default format; MySQL will do the conversion to DATETIME implicitly.
We could do this:
... VALUES ('2020-01-10 18:00:00','2020-01-11 00:00:00')
Or, if we want to use the STR_TO_DATE, we specify a format that matches our string
... VALUES( STR_TO_DATE('2020-01-10 18:00:00','%Y-%m-%d %T')
, STR_TO_DATE('2020-01-11 00:00:00','%Y-%m-%d %T')
)
^^^^^^^^^^^^
Your format strings are wrong. For example, %YYYY should just be %Y; %YYYY means a 4-digit year followed by the literal string YYY.
The format strings should be %Y-%m-%d %H:%i:%s.
See the complete list of format directives here.

Why does MySQL DATE_FORMAT function return NULL when formatting a TIME value?

select DATE_FORMAT('8:48:30 AM', '%H:%i:%s')
It returns Null why ?
but when using
select DATE_FORMAT(CURTIME(), '%H:%i:%s')
It return formatted value.
It's returning NULL because MySQL isn't successfully parsing the string into a valid DATETIME value.
To fix the problem, use the STR_TO_DATE function to parse the string into a TIME value,
SELECT STR_TO_DATE('8:48:30 AM', '%h:%i:%s %p')
Then, to get the TIME value converted to a string in a particular format, use the TIME_FORMAT function, e.g. 24-hour clock representation:
SELECT TIME_FORMAT(STR_TO_DATE( '8:48:30 AM', '%h:%i:%s %p'),'%H:%i:%s')
returns:
--------
08:48:30
The method DATE_FORMAT is used to display date and time, however in the first you are not assigning any date except time, so its is throwing null.
From the manuals -
DATE_FORMAT Formats the date value according to the format string.
In MySql version 5.5 SELECT DATE_FORMAT( CURTIME( ) , '%H:%i:%s' ) returns null
DATE_FORMAT 's first parameter is of type DATETIME. On recent mysql server versions both your queries return NULL.
So the answer to your question is that this difference in behaviour is because of a bug in your mysql version - in some way it converts the TIME to DATETIME, while it cannot convert the string to DATETIME.
Here is also an example of a working query:
select DATE_FORMAT(NOW(), '%H:%i:%s')
NOW() returns a DATETIME while CURTIME() returns TIME.
To my knowledge, I think it's because MySQL recognises the function as a time, and therefore knows how to handle it. Whereas, in the first example, it regards it as a string and doesn't know what to do with it.

compare string to date on mysql

In MySQL 4.0.21-standard, I have a table with a date, saved as a string.
I want to compare this string with a date in my request.
SELECT FE_CLIENT.*
FROM FE_CLIENT
WHERE D_DATFINPUBLI < '2010/06/03'
How can I cast my column date_deb to a date for compare?
Assuming MySQL (if not, retag your question)
Use the MySQL STR_TO_DATE function to put the '2010/06/03' to a DATETIME value.
SELECT FE_CLIENT.*
FROM FE_CLIENT
WHERE D_DATFINPUBLI < STR_TO_DATE('2010/06/03','%Y/%m,%d');
Do the same thing for D_DATFINPUBLI if it's not already a DATETIME format.
EDIT:
SELECT STR_TO_DATE( D_DATFINPUBLI, '%d/%m/%Y %h:%i' ) DD, FE_CLIENT . *
FROM FE_CLIENT
WHERE STR_TO_DATE( D_DATFINPUBLI, '%d/%m/%Y %h:%i' ) < STR_TO_DATE( '04/06/2010', '%d/%m/%Y' )
AND D_CDSTATUPUBLI <> 'EXP'
ORDER BY D_NIDPUBLI
Just format your string to proper format before query execution
or, if you want it strictly with mysql,
WHERE D_DATFINPUBLI < replace('2010/06/03','/','-')
EDIT:
D_DATFINPUBLI field must be of date type and have format of 2010-06-03

Creating DATETIME from DATE and TIME

Is there way in MySQL to create DATETIME from a given attribute of type DATE and a given attribute of type TIME?
Copied from the MySQL Documentation:
TIMESTAMP(expr), TIMESTAMP(expr1,expr2)
With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value.
mysql> SELECT TIMESTAMP('2003-12-31');
-> '2003-12-31 00:00:00'
mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');
-> '2004-01-01 00:00:00'
To get a true DATETIME value from your two separate DATE and TIME values:
STR_TO_DATE(CONCAT(date, ' ', time), '%Y-%m-%d %H:%i:%s')
You could use ADDTIME():
ADDTIME(CONVERT(date, DATETIME), time)
date may be a date string or a DATE object.
time may be a time string or a TIME object.
Tested in MySQL 5.5.
datetime = CONCAT(date, ' ', time);
select timestamp('2003-12-31 12:00:00','12:00:00');
works, when the string is formatted correctly. Otherwise, you can just include the time using str_to_date.
select str_to_date('12/31/2003 14:59','%m/%d/%Y %H:%i');
Without creating and parsing strings, just add an interval to the date:
set #dt_text = '1964-05-13 15:34:05.757' ;
set #d = date(#dt_text) ;
set #t = time(#dt_text) ;
select #d, #t, #d + interval time_to_sec( #t ) second;
However this truncates the microseconds.
I agree with Muki - be sure to take account of time zones and daylight savings time!