Set mysql Zero date results to null or a blank string - mysql

I am using str_to_date() as part of an insert command on a field which either contains a correctly formatted date or a blank string.
For rows with a blank string str_to_date returns a ZERO date of '0000-00-00 00:00:00' as expected.
I can use the IGNORE keyword as part of the INSERT statement to prevent errors, but having the ZERO date in the table leads to issues later when attempting to compare the field to other vales. My goal is to insert either a blank string or a null value. Can anybody point me in the right direction?

One solution would be like this:
insert into mytable
select
case
when varchar_date != '' then str_to_date(varchar_date, 'date_format')
end as date_column,
...
from
...
(whenever varchar_date is not empty, call str_to_date function which will return a valid date if varchar_date is a valid string, and whenever it is empty just return null)

Related

Why MySQL "WHERE" clause approximation: retrieves values even the condition is not met

I have a table which primary key is numeric and auto-incremented.
When I run a query such as:
SELECT * FROM my_table where id = '1a';
The query returns the row with the primary key set to "1".
I was not aware of this behavior, is it possible to prevent it?
I was expecting this WHERE clause to retrieve nothing since the id is "1" and not "1a". It is behaving like it was a LIKE clause.
MySQL implicitly converts a String literal to int while comparing with an int column.
You should really fix your application code (eg: PHP), and properly typecast to (int) before using them in a query. Ideally, your application should not have been inputting string values to compare against an integer field.
Now still, if you don't have control over input value, an approach can be to check if the value is numeric or not, and use it accordingly for comparison. Adapting a sargable approach from https://dba.stackexchange.com/q/89760/160363
SELECT * FROM my_table
WHERE id = CASE WHEN CONCAT('','1a'*1) = '1a' THEN '1a' ELSE NULL END;
mysql automatically converts strings to numbers, and just takes the leading characters that are digits. You could instead explicitly cast the ID to a string:
SELECT * FROM my_table where CAST(id AS CHAR) = '1a';

Copy values one MySQL column to another, but formatted

I have added a DATE column to a table, but now need to populate that DATE column with the values from another column - except that original column is an INT. The INT column is mmddyyyy. Is there a way to copy and format using
UPDATE `table` SET int_column = date_column
Try this using str_to_date and lpad functions:
UPDATE `table` SET date_column = str_to_date(lpad(int_column, 8, 0),'%m%d%Y')
Why used lpad(int_column, 8, 0) - When date is, say, 02012017, the direct cast to char will convert it into 2012017, for which str_to_date function will return null. Lpad pads required 0 to make length 8 and hence outputs 02012017 which str_to_date function will correctly convert.

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.

Unexpected result with MIN function in ms-access caused by text field with empty string

If I use the MIN function on a text field, I get an unexpected result.
I have a table with one text field with following values 'a', '', 'c'.
My expectation is that the empty value is returned (when you would sort the table the empty string comes before the 'a'), but instead I get the 'c' as a result !!!
One should easily be able to see this problem by performing the following queries in an access database:
create table testbug (Field1 varchar (255) NULL)
insert into testbug (Field1) values ('a')
insert into testbug (Field1) values ('')
insert into testbug (Field1) values ('c')
insert into testbug (Field1) values ('d')
select min(field1) from testbug
If the blank value contains something else (even a space for example) then it works correct!
Can anyone reproduce this and/or explain and/or indicate whether this is a known bug (I could not find anything about this).
I work with the following version:
Microsoft Office Professional 2010
Microsoft Access Version: 14.0.7166.5000 (32-bit)
MIN simply ignores NULL values.
If you still want to use MIN with NULL values you can try :
SELECT MIN(Nz(Field1, " ")) FROM testbug
the MIN function indeed seems to handle empty values (zero length string values) as NULL.
I added a Field2 to your testbug table and added two rows manually:
no value for Field1, value 'k' for Field2
value for Field1, value 'l' for Field2, remove value for Field1
I also entered a value 'm' in Field2 for the second row you inserted in your table.
Next, I ran this query:
SELECT Field1, Field2,
IIf(min(Field1) Is Null,'null','not null') AS result, Len(Field1)
FROM testbug
GROUP BY Field1, Field2
The IIF function returns null for all values being null or empty.
For the second row you inserted, the function Len returns 0, meaning this is a zero length value. However, the IIF function returns null.
Meaning, MIN seems to handle empty values as NULL values.
Apparently, this is standard behavior within MS Access.
Hope this helps.
Also hope help here was better than the help you got on Helpmij ;)

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')