How does string truthiness work in MySQL? - mysql

I wanted to look for records where a certain string field was not blank or null, so I simply wrote SELECT ... FROM myTable WHERE x, assuming that blank and null strings would evaluate to false, but that doesn't appear to be the case.
The string "02306" is true, whereas "N06097EIP" is somehow false.
What's going on?
Edit: I'm aware of the workarounds, I simply want to know how the casting works.

In these expression string are first converted to numbers. "02306" is converted to 2306 which is >0 and therefore considered true, while "N06097EIP" (starting with non-digit) is converted to 0, which is evaluated as false.
Compare results of:
select convert("N06097EIP",signed)
and
select convert("02306",signed)

In a boolean context, such as
WHERE x
the expression x will be evaluated as an integer value. Note that MySQL considers a BOOLEAN as a numeric type.
http://dev.mysql.com/doc/refman/5.1/en/numeric-type-overview.html
It doesn't matter what type the expression x is; it's either an INTEGER type, or it will be converted to an INTEGER type, according to the documented conversion rules.
The end result is that the expression x will be evaluated to be either NULL, integer zero, or integer non-zero.
And those correspond to the boolean "truthiness" values of NULL, FALSE and TRUE.
The reason '02306' is considered TRUE is because this string converts to integer value 2306, which is non-zero.
The reason 'N06097EIP' is considered FALSE is because this string converts to integer value 0.
To can run a simple test case to verify:
SELECT IF( 0 = 'N06097EIP', 'is zero', 'is not zero')
SELECT 0 = 'N06097EIP'
The behavior you observe is entirely expected. It's all pretty straightforward. You may have been caught unawares, because the normative pattern is for us to avoid this type of evaluation and to instead use "workarounds" (as you put it) to return a boolean.

Don't try to be too cute about this with syntactic shortcuts. If nothing else, it's always harder on the next developer who has to figure out what you were doing.
Just spell out what you want.
SELECT *
FROM myTable
WHERE x IS NOT NULL AND x <> '';
or, if you'd prefer:
SELECT *
FROM myTable
WHERE COALESCE(x, '') <> '';

Related

How can I avoid autocoercion in Couchbase queries?

An N1QL query has a filter WHERE myField < $value.
From experimenting, I see that Couchbase orders the types as follows: boolean < integer < string < JsonArray, even though from my perspective they should not be comparable.
For example, any boolean evaluates as less than any integer; any integer is less than all strings. (9223372036854775807 (Long.MAX_VALUE) evaluates as less than "" (empty string).)
I want to avoid this type-coercion. I want "A" < 1 and "A" > 1 to be false and not to return such values from the filter. (And also, it seems that in Javascript, both these expressions are false, as they should be.)
What are the coercion rules? How do I prevent this?
You have discovered the collation order of N1QL. Here is a fuller explanation:
https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/datatypes.html
If you want to avoid this comparison across types, you can add a clause using the TYPE() function to verify that the two elements being compared are of the same type.
https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/typefun.html
So rather than having $A > 3 you would have ($A > 3) AND (TYPE($A) = TYPE(3)).

SSRS Iif Evaluates True and False

MSDN states that SSRS will evaluate both the true and false part of an Iif statement regardless of which one is returned. This seems to make Iif completely useless in regard to error avoidance. In other words, you cannot use Iif to skirt around an error, so essentially any operation you choose to include must always be valid regardless of the conditions. Honestly, what good is this?
So my question is... Does SSRS have other ways of evaluating conditions besides Iif?
Here is my example. I just want to be able to return Left without grabbing the first character of the match.
=Iif
(
InStr(Fields!SearchField.Value, Fields!Criteria.Value) <= 1,
"",
Left(Fields!SearchField.Value, InStr(Fields!SearchField.Value, Fields!Criteria.Value)-1)
)
However, what is happening here is that InStr(Fields!Criteria.Value, Fields!Criteria.Value)-1 is evaluating to 0 in some cases, which is perfectly fine until the FALSE part of the statement tries to deduct 1 from it and pass it into the InStr function. InStr cannot accept -1 as the number of characters to return.
An oversimplification of this is as follows. Assume you have a situation where Value can never fall below 0 without throwing an error.
Iif (Value > 0, Value = Value -1, 0)
Trying to use Iif to force the value not to fall below 0 does not work because all of these statements get evaluated even if they do not meet the conditions.
Trying to use InStr to get an index on a match, and Left to build a substring based on that index fails because of this. I have no idea how to completely avoid the condition.
I too thought Switch would work, but upon testing it did not. As far as I can tell, custom code is the only way to go. I tested the function below which worked for my few test cases.
Public Function TruncateWord(ByVal str As String, ByVal criteria As String) As String
If str.Contains(criteria) Then
Return Left(str, InStr(str, criteria) - 1)
Else:
Return ""
End If
End Function
I tested with the below 5 basic strings, searching for "d", and got the following results:
+-----------------+
| String | Result |
+-----------------+
| asdf | as |
| asd | as |
| as | |
| da | |
| ad | a |
+-----------------+
So this appears to work for all 3 possible cases (InStr returns > 1, InStr returns 1, and InStr returns 0) from my limited testing.
Here is the final result from C Black's suggestion to use custom code. I had eventually hoped to use the segment of the string to format the match in a different color in the opposite column. I had to add some html tags. It works perfectly. Thank you all for your assistance.
Code block:
Public Function ParseMatch (ByVal FullString As String, ByVal Criteria As String) As String
Dim Segment(2) As String
Dim Result As String
If FullString.ToUpper.Contains(Criteria.ToUpper)
Segment(0) = Left(FullString, InStr(Ucase(FullString), Ucase(Criteria) )-1 )
Segment(1) = Criteria
Segment(2) = Right(FullString, Len(FullString) - Len(Segment(0)) - Len(Criteria))
Result = Segment(0) & "<b><FONT color=blue>" & Segment(1) & "</FONT></b>" & Segment(2)
Else
Result = FullString
End If
Return Result
End Function
Report cell:
=Code.ParseMatch(Fields!Defendants.Value, Fields!Firm_Client_Name.Value)
If the name is found in the list of defendants, it colors the text blue in that field and bolds it.
Use SWITCH
SWITCH stops evaluating expression as soon as the first True is found. Switch works with pairs (an expression to evaluate and a result if it's true). The final True acts like an else.
=SWITCH
(
InStr(Fields!SearchField.Value, Fields!Criteria.Value) <= 1, "",
True, Left(Fields!SearchField.Value, InStr(Fields!Criteria.Value, Fields!Criteria.Value)-1)
)
I rewrote it for readability:
=Switch
(
InStr(Fields!Defendants.Value, Fields!Firm_Client_Name.Value) = 0, "",
InStr(Fields!Defendants.Value, Fields!Firm_Client_Name.Value) = 1, "",
True, Left(Fields!Defendants.Value, InStr(Fields!Defendants.Value, Fields!Firm_Client_Name.Value)-1)
)
' 0 = Error
' 1 =
' >1 = substring based on criteria
1 and >1 are correct, but I still get the error when the InStr evaluates to 0.
The thing is, I have to tell the Left function -1 or it will return the first letter of the delimiter, which I do not want. Even though the condition of InStr(Fields!Defendants.Value, Fields!Firm_Client_Name.Value) = 0 is true, instead of returning "" for the column, it returns an error. This tells me it is still being evaluated despite it being outside of the specified condition.
If I omit the -1 within the Left function, no error results. Yet I get substring + first letter of delimiter.
I work with sensitive information, so I cannot give specific results of the strings.

Return true when query gives 1

I want to save a true/false in my MySQL database. I'm saving 1/0 in an INT column to do this. When I select it, I get the 1 or 0, but I want it to return true/false to my PHP code, without having to rewrite the database.
Can I use another column type? Should I save it differently?
Update: My question is about not wanting to rewrite the returned value. I'm getting a lot of results from my database. Many of those are true/false, but some are 0s because the price is 0, so I don't want to universally rewrite all 1s and 0s. I also don't want to manually rewrite 10 columns.
To follow up my comment, here's a more detailed response which also covers the PHP side, although this probably belongs on StackOverflow.
I've always just used tinyint, although you can use bool/boolean which are synonyms for tinyint(1)
However as of MySQL 5.0.3 you can use the bit type:
As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64.
Next, assuming you have an active column, perhaps to store if a user is active, you could use PHP's automatic type conversion to handle this quite simply.
// Obviously you'd replace this with your database call
$results = [['active' => 1], ['active' => 0]];
foreach($results as $row) {
if ($row['active'] == true) {
echo "true\n";
}
else {
echo "false\n";
}
}
You don't strictly need to do anything.
PHP does not, and can not, use strongly typed variables. So, if you receive an (int) 1 from your query results, you can simply use this 1 as a boolean without rewriting or changing anything.
$intOne = (int) 1; //explicitly treat the variable as an integer
var_dump((bool) $intOne); //treat the variable as a boolean
When used in any boolean context, like if ($variable)... then any of these types will be considered to be false by PHP:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
... And, most importantly;
Every other value is considered TRUE (including any resource).
Source: PHP Manual > Booleans (english)
So while you can change the storage type of your column in mysql, this won't really change the way PHP handles the variable retrieved from your results at all.
Historically, I've always used a column of type TINYINT(1) to store boolean values in mysql, and as Tom Green points out, recent mysql versions provide a new BIT type, which might be appropriate. To the best of my knowledge, mysql does not currently have an actual boolean data type.
You could just as easily use a column of type VARCHAR(1), though, because PHP can and will use any value as a boolean, thanks to the glorious, majestic, and sometimes maddening, PHP Type Juggling.
If you're trying to use the values you're retrieving for boolean logic, just use the values you receive from mysql like booleans and it will work:
if ($valueFromResults) {
//The value was something like true
} else {
//The value was something like false
}
If you're trying to actually echo out the words "true" and "false", then you're probably best served by explicitly echoing the words out yourself, like this;
if ($valueFromResults) {
echo "true";
} else {
echo "false";
}
or, in my preferred shorthand;
echo ($valueFromResults) ? "true" : "false" ;
Update You mentioned in a comment that you want to pass the values through json_encode() and use them in javascript.
JavaScript treats any real value, like int 1, as true and any empty value, like int 0, or an empty string, as false. So if your json_encode() output gets used in actual JavaScript, the int values will still work as boolean values. So the integer values from your database should still work as they are.
Just check that your integer results are encoded as integers by PHP and not as strings - they should be encoded correctly by default - because "0" == true in javascript, but 0 == false.
For a boolean value (true/false), you should use the mySql type bit or tinyint(1).
$boolean = $mysql_data ? true : false;

Difference between conditionals

Just wanted to know if someone can explain the difference between these two conditionals:
if ( !object )
if ( object == null )
where object is an instance of a user-defined class.
I'm sure that these two cannot be used in an interchangeable manner, or are they?
Thanks.
The effect is in practice the same, so I guess you could say they're interchangeable.
In a boolean context (such as a conditional), an expresion is evaluated to either true or false.
In Actionscript 3.0, the following values evaluate to false:
false
null
0
NaN
"" (the empty string)
undefined
void
Everything else evaluates to true.
A reference to an user-defined class instance can either be null or not null.
So, in this case:
if ( object == null )
Obviously, the condition is met only if object is null.
In this other case:
if ( !object )
The expression object will evaluate to false if object is null. If it is null, the expression is false. Since this is in turn negated, the final value will be true and so the condition will be satisfied. So, just like in the first case, if object is null, the condition is met. And like in the first case, again, if object is not null, the condition is not met.
There's no other option if your variable is typed to a user-defined class; such a variable can only contain a valid reference or null; i.e. it can't hold any value evaluable to false in a boolean context, except for null; so, again, it's either null or not null. Which is why both code samples have the same effect.
The first is making a boolean comparison. If the object is false, the not(!) operation will make the condition true, if the object has a value other than false the statement will fail.
The second conditional is evaluating if the object has the value of null or not.
The reason these may be interchangeable is that various languages allow some equivalence between 0, false, null (or "\0") and other values of similar meaning.
I do not know actionscript, but testing equivalence of false, null, 0 etc., or reading the docs on boolean values, will be of some benefit.
Sure not :)
The first one means that the proposition is true only if different from the object;
The second one is true only if the object equals to null.
"!" means "is not the object"
"==" means that the the object has to have the value equal to the one at the right of the symbol

Access Vba - To find null and blank values

I am trying to find the blank values and null values in a table. I am using Asc to assign the values of the table to a variable and then based on their ASCII values differentiating null and blank. But I am getting "runtime error 94: Invalid use of null" when the code tries to read the ASCII value of a null field.
When I have to deal with return values that can be either Null or zero-length string, I use a function that converts ZLS to Null:
Public Function varZLStoNull(varInput As Variant) As Variant
If Len(varInput) = 0 Then
varZLStoNull = Null
Else
varZLStoNull = varInput
End If
End Function
This takes advantage of the fact that the VBA Len() function treats a Null and a ZLS exactly the same so that you don't have to handle each case individually.
However, remember that if you use this in a WHERE clause, you'll be losing performance because it can't use the indexes. Thus, in a WHERE clause, you'd test for IS NULL or =""
SELECT MyField
FROM MyTable
WHERE MyField Is Null Or MyField = ""
That will be much more efficient. The varZLSToNull function is most useful when you're appending processed data to a field that has ZLS Allowed set to NO (as it should).
Another thing you should consider is changing your field so that it disallows ZLS, then running a query (using the WHERE clause above without the Is Null) to replace all the ZLS's with Nulls.
Of course, that assumes that your data is not distinguishing between Null and ZLS as meaning two different things (Null meaning "we haven't recorded any value here" and ZLS meaning "we have recorded an empty value here").
You can try the following user-defined function to test the table value:
Public Function text_test(str_in as Variant) As Long
' given input str_in, return -2 if input is Null,
' -1 if input is zero-length string; otherwise return 0
' use function Nz to test if input is Null and return -2,
' otherwise check non-null value with Len
' and return -1 if it is a 0-length string,
' otherwise return 0 for anything else
text_test = IIf(Nz([str_in], "null") = "null", -2, _
IIf(Len(str_in) = 0, -1, 0))
End Function
In the immediate window run a test with different inputs:
?text_test("fred");text_test("");text_test(Null);text_test(9);text_test(False)
Should return:
0 -1 -2 0 0
Note that you cannot use str_in as string in the function declaration since this will cause the same error you refer to in your question.
I think you should be using IsNull() to decide if a value is null.
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5034252.html
encapsulate your code inside a if statement and compare the string value to vbNullString like this:
If (Not (<string> = vbNullString) Then
if the string is NOT null execute your original code
if it is null add an Else block to execute what you need to do if the value is null
Yeah, it's an old thread, big deal...
This is the most concise way to test a value for Null and zero-length that I've seen:
FinalValue = IIf(Not Len(Nz(Value, "")) = 0, Value, Null)
How it might perform compared to David Fenton's excellent Function above, I do not know. I do know that the one-liner I present here and David's function do almost exactly the same thing. I suspect the one-liner might perform a bit better than a call out to a Function. On the other hand it makes use of an inclusive If, so it may in fact be slower. Who knows?
I use it in Class modules, mainly. For example, when creating a record with a DAO Recordset:
With rst
.AddNew
!JobCardID = IIf(Not m_JobCardID = 0, m_JobCardID, Null)
!ConstructionProjectID = IIf(Not m_ConstructionProjectID = 0, m_ConstructionProjectID, Null)
!MajorDisciplineID = IIf(Not m_MajorDisciplineID = 0, m_MajorDisciplineID, Null)
!ActivityDescriptorID = IIf(Not m_ActivityDescriptorID = 0, m_ActivityDescriptorID, Null)
!ActivityStatus = IIf(Not Len(Nz(m_ActivityStatus, "")) = 0, m_ActivityStatus, Null
'etc...
End With
In the above code, ActivityStatus is the relevant String.
Note: I never design a database with fields allowing zero-length strings. Repeat: NEVER.