SQL(phpMyAdmin): Change Column Format of Date With Command - mysql

i have a column with name 'expdate' with type 'varchar' with values like this:
2021-02-27
28-02-2023
29/02/2024
.
.
.
now i want change all date values like format %d-%m-%Y to the %Y-%m-%d and save to new column with type date and use:
UPDATE `Users`
SET `fixed_expdate` = STR_TO_DATE(REPLACE(`expdate`,"/",'-'), "%d-%m-%Y")
where `expdate` != '0000-00-00'
but sql command show error like:
SQL query:
UPDATE `Users` SET `fixed_expdate` = STR_TO_DATE(REPLACE(`expdate`,"/",'-'), "%d-%m-%Y") where `expdate` != '0000-00-00'
MySQL said: Documentation
#1411 - Incorrect datetime value: '2021-02-27' for function str_to_date
i need to sql command,What is your solution?

You must use different converting expressions for each separate source data format. And you must check that only the values which matches the pattern used in current query are included into the convertion.
This can be performed using a lot of separate queries, each converts one of existing source formats.
-- convert the dates which have correct format
UPDATE `Users`
SET `fixed_expdate` = `expdate`
WHERE `expdate` REGEXP '\d\d\d\d-\d\d-\d\d';
-- convert dated which looks like 28-02-2023
UPDATE `Users`
SET `fixed_expdate` = STR_TO_DATE(`expdate`, "%d-%m-%Y")
WHERE `expdate` REGEXP '\d\d-\d\d-\d\d\d\d';
-- convert dated which looks like 29/02/2024
UPDATE `Users`
SET `fixed_expdate` = STR_TO_DATE(`expdate`, "%d\/%m\/%Y")
WHERE `expdate` REGEXP '\d\d\/\d\d\/\d\d\d\d';
-- and so on
After each separate convertion (or after a lot of convertions) you may look at the rows which were not converted
SELECT `expdate`
FROM `Users`
WHERE `fixed_expdate` IS NULL
LIMIT XXX
and build the next converting expression for a pattern which was not used yet - until all values are successfully converted.
MySQL said: Documentation
#1411 - Incorrect datetime value: '2021-02-27' for function str_to_date
This is due to 2 separate formats which differs in day and month posession (which are swapped) - they cannot be distinguished easily. You must use additional checking if both formats are present in the data. And you cannot distinguish what format must be applied if both formats are possible (for example, when the value is '01/02/2021').
UPDATE (copied from the comment)
Your regular expressions should should probably have anchors for the beginning and end of the string ('^' and '$'). – Gordon Linoff

Related

inner join two datasets but return nothing without any error (date format issue)?

I'm new to SQL, currently I'm doing a task about join two datasets, one of the dataset was created by myself, here's the query I used:
USE `abcde`;
CREATE TABLE `test_01`(
`ID` varchar(50) CHARACTER SET latin1 COLLATE latin1_bin DEFAULT NULL,
`NUMBER01` bigint(20) NOT NULL DEFAULT '0',
`NUMBER02` bigint(20) NOT NULL,
`date01` date DEFAULT NULL,
PRIMARY KEY (`ID`, `date01`))
Then I load the data from a csv file to this table, the csv file looks like this:
ID NUMBER01 NUMBER02 DATE01
aaa=ee 12345678 235896578 **2009-01-01T00:00:00**
If I query this newly-created table, it looks like this(the format of the 'DATE01' changes):
ID NUMBER01 NUMBER02 DATE01
aaa=ee 12345678 235896578 **2009-01-01**
Another dataset, I queried and exported to a csv file, the format of the date01 column is like 01/12/1979 and in SQL the format looks like 1979-12-01.
I also usedselect * from information_schema.columns to check the datatype of the columns I need to join, for the newly-created dataset:
The date column for another dataset is:
The differences are:
1. The format of the date column in csv appears different
2. The COLUMN_DEFAULT are different, one is 0000-00-00, another one is NULL.
I wonder the reason why I got empty output is probably because the difference in the 'date' format, but I'm not sure how to make them the same so that I can get something in the output, can someone gave me some hint? Thank you.
the format of the 'DATE01' changes
Of course, DATE datatype does not contain timezone info/component.
I wonder the reason why I got empty output is probably because the difference in the 'date' format
If input value have some disadvantage (like wrong data format) than according value is truncated or is set to NULL. See - you must obtain a bunch of warnings during the importing similar to "truncate incorrect value".
If the date field in CSV have wrong format then you must use intermediate user-defined variable for accepting raw value, and apply proper converting expression to it in SET clause. Like
LOAD DATA INFILE ...
INTO TABLE tablename (field1, ..., #date01)
SET date01 = STR_TO_DATE(#date01, '%d/%m/%Y');

MySQL 5.7 date field trouble

I have installed recently MySQL 5.7 . Something weird is happening with a date column.
If I execute a SELECT query using that field in a WHERE section, I have a resultset, but when I use the same WHERE condition to UPDATE a row I get an Invalid date format error message.
Here is the SELECT sentence:
SELECT *
FROM
FDpoCargTran
WHERE FDpoCargTran.Banco = '001'
AND (FDpoCargTran.Conciliacion = '' OR FDpoCargTran.Conciliacion IS NULL)
AND FDpoCargTran.Fecha = '2016-09-27'
This sentence returns 2 rows resultset, that's ok.
Now, Here's the UPDATE sentence:
UPDATE
FDpoCargTran
SET
Edo = 'C'
WHERE FDpoCargTran.Banco = '001'
AND (FDpoCargTran.Conciliacion = '' OR FDpoCargTran.Conciliacion IS NULL)
AND FDpoCargTran.Fecha = '2016-09-27'
AND Deposito = 1041
And I get this error message:
Data truncation: Incorrect date value: '' for column 'Conciliacion'
The Conciliacion columns is defined as:
`Conciliacion` date DEFAULT NULL,
If I remove the Conciliacion = '' condition, everything works fine.
Why empty string is not valid to evaluate the column in an UPDATE sentence and not in a SELECT?
Please, an idea!!!
Basically, for date datatype, you cannot store something like White
Spaces or ' ' strings. You need to make the column to accept NULL
values and insert an actual NULL into it. This is not a problem in MySQL 5.7, its how date is set in databases.
Update is a DML statement, when you actually want to write something into table, or check for a condition, MySQL is unable to understand what ' ' is for the date column type.
So, you cannot have ' ', instead you can have NULL set. Thats how MySQL can check the condition and make appropriate changes!!
I would suggest, change it to NULL.
Alter your datetime column to varchar.
Import whatever table/database.
Update FDpoCargTran set Conciliacion=NULL where Conciliacion='';
Alter column back to datetime.

Converting String Data Value into date

Good Morning All;
I currently have a MySQL table where there are 3 date fields (Columns) that were loaded as strings in this format 20140101 YYYYmmdd. I would like to convert this to a date format 2014/01/01 YYYY/mm/dd. Can someone please provide a simple sql syntax that would alter the table to a date format from a string and change the column to display the dates like this 2014/01/01 and not like 20140101. Thanks to all
Try this:
date_format(str_to_date(datecolumn, '%Y%m%d'),'%Y/%m/%d')
If you just want to reformat the values in the VARCHAR column, assuming that the column with sufficient length e.g. VARCHAR(10), and all the values are eight characters in length...
You could do something like this:
UPDATE mytable t
SET t.mycol = CONCAT( LEFT( t.mycol ,4)
, '/'
, SUBSTR( t.mycol ,5,2)
,'/'
, SUBSTR( t.mycol ,7,2)
)
WHERE CHAR_LENGTH(t.mycol) = 8
We want something in the statement that will prevent the statement from "working" a second time, if it's inadvertently re-run. It doesn't have to be CHAR_LENGTH. We might want to include a check that the value doesn't already contain a slash character AND t.mycol NOT LIKE '%/%'.
But why on earth are "date" values being stored in character columns, rather than in DATE datatype, which is custom designed for storing and working with date values?
ALTER TABLE mytable MODIFY mycol DATE ... ;
(If the column is defined as NOT NULL, has a default value, has a comment, those attributes can be retained, they need to be included in the new column specification, e.g.
ALTER TABLE mytable MODIFY mycol DATE NOT NULL COMMENT 'creation date';
Note that DATE columns do not have a "format" per se. When converting to string, MySQL uses date format '%Y-%m-%d'. And MySQL expects string literals representing date values to be in that same format. To get a value from a DATE column converted to string in format 'yyyy/mm/dd'.
SELECT DATE_FORMAT(date_col,'%Y/%m/%d') AS date_col
To get a string value in that format converted to DATE datatype
SELECT STR_TO_DATE('2015/06/01','%Y/%m/%d')

Convert varchar column to date in mysql at database level

I have one column date1 which is varchar type
I want this column to date type.
I tried changing field but all date is converted to 0000-00-00.
format is dd-mm-yyyy but in varchar.
How can I convert the same date format but with date format using sql queries or similar but at database level ?
UPDATE `table`
SET `column` = str_to_date( `column`, '%d-%m-%Y' );
More about STR_TO_DATE function.
Since your column name is date1, you can replace column with date1 in the above syntax, and the code shall be:
UPDATE `table`
SET `date1` = str_to_date( `date1`, '%d-%m-%Y' );
The other answers here are risky, because if they go wrong you'll lose your data. A safer way to do this is to create a new field on your database with a DATE (or DATETIME if you need time as well) format, then to run a query like
UPDATE `table` SET `my_new_date_field` = STR_TO_DATE( `my_old_data_field`, '%d/%m/%Y');
In this way, if the %d/%m/%Y bit is wrong, you won't lose your data.
Once you're happy, you can delete the old data field and rename the new one.
use STR_TO_DATE Function of MySQL
FIRST you will need to update the value in date format.
UPDATE `tbl` SET `date1` = STR_TO_DATE(`date1`, '%d-%m-%Y') WHERE 1=1
THEN Convert the field to date.
Most importantly remember to insert date as Y-m-d format, after then.

mysql change date format

I have a date field (tinytext) holding date information in format of "dd-mm-yy" e.g 07-01-90. Using a mysql query I want to change it to yyyy-mm-dd date format. I tried the code below but nothing happens.
mysql_query("UPDATE Table SET date=STR_TO_DATE('date','%Y,%m,%d')");
You're using the correct function STR_TO_DATE(str,format) to achieve the goal, but you're making two mistakes:
In your query the format argument does not match the string expression format. You said it's in dd-mm-yy format while you passed %Y,%m,%d (comma separated) to the format argument. The query will return a "incorrect datetime value" error. You should use %d-%m-%Y.
You can't change data type of a column on the fly, by setting different type of the value being passed. You have to first update the values and then change data type for column.
So, summarizing:
mysql_query("UPDATE `Table` SET `date` = STR_TO_DATE(`date`, '%d-%m-%Y')");
mysql_query("ALTER TABLE `Table` CHANGE COLUMN `date` `date` DATE");
Additionally, consider switching to the recommended PDO extension in place of old and slowly deprecated mysql extension.
Error in your query
is STR_TO_DATE(date, '%Y-%m-%d')
mysql_query("UPDATE Table SET date=STR_TO_DATE(date,'%Y-%m-%d')");
Try this:
INSERT INTO table(date_field) VALUES(STR_TO_DATE('December 8, 2010','%M %d,%Y'));
Try it with DATE_FORMAT() function.
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y,%m,%d')");
To display 2 digit year
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%y-%m-%d')");
To display 4 digit year
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y-%m-%d')");
I'd say you have to do this:
UPDATE table_name SET date = DATE_FORMAT('date', %Y-%m-%d);
If you are using my_sql with php, you can use date function