Why is CASTing VarChar to DateTime resulting in null? - mysql

I'm running MySQL and trying to convert the following row from VarChar to DateTime
+-------------------+
| review_date |
+-------------------+
| May 24, 2015 |
| June 3, 2013 |
| December 19, 2003 |
+-------------------+
I have tried CAST(review_date as DATETIME) However that results in a column of null values when I test it in the SELECT statement.
I also tried CONVERT(DATETIME, review_date, 107) however, it resulted in: 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 'review_date, 107) at line 3
I haven't converted to date time before but I can't understand how the above statements deviate from the documentation or why they wouldn't be working.
I used this syntax to create for the column: review_date varchar(255) DEFAULT NULL. And STR_TO_DATE(review_date, '%m/%d/%Y') also yields a column of Null cells.

The problem is when you cast or convert, your string value isn't in the standard yyyy-mm-dd format.
If you run this example, you will see what I mean. This example also has the proper way to convert string to date:
SELECT
CAST(review_date AS DATETIME) -- gives null due to incorrect format
, STR_TO_DATE(review_date, '%M %d, %Y') -- gives correct date
, CAST('2015-05-24' AS DATE) -- gives date due to correct format
FROM
date_test

This is for MYSQL (where I converted my string to date function)
SELECT cast(str_to_date(column_name), '%m/%d/%y') as date)
FROM Table Name;
Example:
SELECT cast(str_to_date(Release_Date, "%m/%d/%y") as date)
FROM movie-data;
Make sure that you use the delimiter in your date format correctly. Like in my case the date was in the string column was separated by '/'. In your case it might be separated with a comma ',' or dot '.'. Make sure you use that.
Example: 3/8/2016 "%m/%d/%y"
3,8,2016 "%m,%d,%y"
3.8.2016 "%m.%d.%y"

Related

Change date string with "am/pm" to actual date in MySQL

I have a column of dates written as strings with "am" and "pm" at the end, for example:
1/1/2016 12:00:00.000 AM
The type of the column is currently varchar, I want to change the type to datetime format.
Attempt 1
Changing the column type from phpmyadmin dashboard gives the following error:
Query error:
#1292 - Incorrect datetime value: '1/1/2016 12:00:00.000 AM'
Attempt 2
Considering the format of the date, I tried to use the STR_TO_DATE function. But it does not give the expected result. It instead returns the same date for each row.
SELECT STR_TO_DATE(`assembling-machine-tag`.`Time`, "%Y") from `assembling-machine-tag`
Result
So, how can I change the format of my column from varchar (with format = dd/mm/yy hh:mm:ss.ms AM) to datetime (with format = yyyy-mm-dd hh:mm:ss) in MySQL 7.4.1?
You just need to use the correct pattern:
SELECT STR_TO_DATE('1/2/2016 01:02:03.456 AM', '%e/%c/%Y %h:%i:%s.%f %p')
-- 2016-02-01 01:02:03.456000
In order to convert varchar data to datetime, you first need to create a temporary datetime column and update it like so:
UPDATE t SET `datetimetemp` = STR_TO_DATE(`varchardate`, '%c/%e/%Y %h:%i:%s.%f %p')
Once satisfied with result drop, the varchar column and rename the temporary column.
I would use this version:
SELECT STR_TO_DATE('1/1/2016 12:00:00.000 PM', '%d/%m/%Y %h:%i:%s.%f %p')

Compare Dates using Between with Column Type VARCHAR

I have a database table called UPDATES that has some logs inserted to. In this table, there is a column called Time. This time column is of type VARCHAR. I had no choice but to make it VARCHAR because there are updates with corrupt time like, 2013-04-04 00xcdww and sometimes like 2013-4-2 with some non ASCII values. So if the Column type was DATETIME, the insertions of that datetime couldve triggered an error.
Now i am in the phase of doing a comparison between two dates to get range of results.
So my question is, will using a VARCHAR compare the dates correctly ?
doing :
Date(Time) BETWEEN 2013-03-02 AND 2013-03-02
Or will this return invalid results ? if it does can you tell me what this query will return that is not within the range specified ?
Yes you need to convert the varchar to date format using STR_TO_DATE
WHERE STR_TO_DATE(Time, '%Y-%m-%d')
BETWEEN '2013-03-02' AND '2013-03-02'
mysql> select STR_TO_DATE('2013-04-04 00xcdww', '%Y-%m-%d') ;
+-----------------------------------------------+
| STR_TO_DATE('2013-04-04 00xcdww', '%Y-%m-%d') |
+-----------------------------------------------+
| 2013-04-04 |
+-----------------------------------------------+
STR_TO_DATE is not enough you have to use SUBSTR function to get first 10 VARCHAR.
SELECT *
FROM `TABLE_NAME`
WHERE STR_TO_DATE(substr(`Time`,1,10), '%d/%m/%Y' )
BETWEEN '2013-03-02'
AND '2013-03-02'
This will avoid you from doing casting which affects the performance of the query.
Updated
As your database column may be 2013-04-04 00xcdww and sometimes like 2013-4-2 so you should use this query,
SELECT *
FROM `TABLE_NAME`
WHERE STR_TO_DATE(`Time`, '%d/%m/%Y')
BETWEEN '2013-03-02'
AND '2013-03-02'

MySql Character to Date Format conversion returns null

I have a char field which is having Date in it as '26-Nov-2011'
I want this date to be printed in YYYY-MM-DD format.
I used following date conversion which is not allowing me to do.
select date_format('26-Nov-2011','%d-%b-%y')
returns Null.
I know date_format function can accept date in YYYY-DD-MM format but
Please let me know how to convert a Character to Required Date Format
Try this:
SELECT STR_TO_DATE('26-Nov-2011', '%d-%b-%Y') dte;
Output:
2011-11-26
You can use STR_TO_DATE() to convert your strings to MySQL date values and ORDER BY the result
STR_TO_DATE(datestring, '%d/%m/%Y')
STR_TO_DATE can be used with this format '%d-%M-%Y', which will match the format of your current date string. Otherwise it will return null. Check on date formats as well.
select str_to_Date('26-Nov-2011','%d-%M-%Y')
from table1
;
Output:
| STR_TO_DATE('26-NOV-2011','%D-%M-%Y') |
-----------------------------------------
| November, 26 2011 00:00:00+0000 |
SQLFIDDLE DEMO

MySQL convert YYYY-MM-DD to unix timestamp

I want to convert a YYYY-MM-DD column to unix timestamp. Similar to this question: MySQL - Convert MM/DD/YY to Unix timestamp
MySQL does not seem to transform a value of '2012-05-10' to the correct unixtime. Here is the suggested function that fails:
SELECT UNIX_TIMESTAMP(CAST(dateid AS DATE)) AS unixtime
What version of MySQL you are using? As tested by MySQL 5.5.27 in SQLFiddle these two queries worked
SELECT UNIX_TIMESTAMP(CAST('2012-05-10 00:00:00' AS DATETIME)) As UnixTime;
SELECT UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE)) As UnixTime;
SQLFiddle Demo
I'm not sure what the problem you are having exactly, but the following works fine:
CREATE TABLE ex (dt VARCHAR(20));
INSERT INTO ex SET dt = '2012-05-10';
SELECT
UNIX_TIMESTAMP('2012-05-10') ex1,
UNIX_TIMESTAMP(dt) ex2,
UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE)) ex3,
UNIX_TIMESTAMP(CAST(dt AS DATE)) ex4
FROM ex;
returns:
+------------+------------+------------+------------+
| ex1 | ex2 | ex3 | ex4 |
+------------+------------+------------+------------+
| 1336633200 | 1336633200 | 1336633200 | 1336633200 |
+------------+------------+------------+------------+
As you can see, there is no need to CAST() if the string is in the form YYYY-MM-DD or YYYY-MM-DD HH:MM:SS, as MySQL implicitly converts strings in this format to DATEs.
See http://sqlfiddle.com/#!2/1a215/3

How to get a total days count

Using MySQL & SQL Server
ID sDate
001 03/06/2010
002 07/08/2010
....
....
sDate Datatype is varchar
Format mm/dd/yyyy
I want to take the date count means How many days is still there, It should compare the system date...
How to convert my varchar to datetime datatype, then how to compare the mysdate to system for getting the totalday counts
sDate - SystemDate = Totalday
ExpectedOutput
ID sDate Totaldays
001 03/07/2010 3 days
002 07/07/2010 7 days
.....
How to make a query for this condition. Need query help.
Your question states MySQL & SQL Server so here is both:
SQL Server datediff function:
SELECT ID, DATEDIFF(DAY, GETDATE(), CONVERT(DATETIME, sDate)) FROM TABLE
MySQL datediff function:
SELECT ID, DATEDIFF(CURDATE(), STR_TO_DATE(sDate, '%c/%d/%Y')) FROM TABLE
This uses the STR_TO_DATE function to convert the varchar to a date and assumes that the format of your date strings is in the format month/day/year.
Gopal, in response to your "How to convert varchar to datetime in mysql...", it's easy:
ALTER TABLE sometable CHANGE sDate sDate datetime;
and MySQL will happily attempt to convert the values for you. However, if it can't properly parse the original date string, that record's sDate will get set to NULL or 0000-00-00. You'll have to massage the sDate field first to convert it to a more normal MySQL format for date strings, which is YYYY-MM-DD. A bruteforce hack would be:
UPDATE sometable SET sDate=CONCAT(
SUBSTR(sDate, 6, 4),
'/',
SUBSTR(sDate, 3, 2),
'/',
SUBSTR(sDate, 0, 2)
);
Of course, this is assuming that your dates are in DD/MM/YYYY format. If they're MM/DD/YYYY, then just swap the middle and last SUBSTR calls. Once this update's completed, then you can use the ALTER TABLE to change field types.
And of course, for anything that affects the entire table like this, make sure you have a backup of it first.