If Statement in MySQL Select - mysql

According to the docs a if works as follows:
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3 [...].
Here is a random fiddle that represents my problem: http://sqlfiddle.com/#!9/8076e2/1
Basically what I'm trying to do is the following:
SELECT IF(whatever, 1, 2) FROM testing WHERE whatever = 'abc';
Since there is a record there that matches my WHERE clause it basically means that whatever won't be 0 or NULL like specified in the docs. Then why am I getting expression3 as result?

expr1 is intended to be a boolean expression, or at least a numeric value, not a string.
You can use true and false, or 1 and 0, etc. Technically any non-zero numeric value is interpreted as true.
Since you are using the string 'abc' as expr1, MySQL is implicitly converting that to the number 0, which represents false.
In order to return one result for a non-empty string, and another result for empty string or null, you can use a query like this:
SELECT if((whatever is not null and whatever != ''), 1, 2)
FROM testing
WHERE whatever = 'abc';
You can also do the same thing with CASE if you want to follow the SQL standard:
SELECT (case when (whatever is not null and whatever != '') then 1 else 2 end)
FROM testing
WHERE whatever = 'abc';

SELECT IF(COUNT(whatever) > 0, 1, 2) FROM testing WHERE whatever = 'abc';

Related

SQL Query on considering a like statement

I am trying to add a column, YES/No, based on text involved. If the Value column contains BALL, we mark it as Yes in the column. But if the 'BALL' is attached with any text/string, it should return it as 'NO'. There are some cases which I have attached
How do I form the case statement so that if any text/string is attached to the 'BALL' without a space should be No, and rest all the cases should be 'Yes'. I tried using like %BALL%, but it does not satisfy all the examples in the above screenshot.
Just insist that the previous and next characters are not letters:
(case when value regexp '([^a-zA-Z]|^)BALL([a-zA-Z]|$)'
then 'YES' else 'NO'
end)
Here is a db<>fiddle.
Set #val variable with value need to lookup:
SET #val := 'BALL';
Run query with two type of checking:
Use LOCATE to find #val value in the table; will return numerical position of the first character of the searched value.
Use SUBSTRING to get two sets of value from string_val column; using the numerical position that was obtained using LOCATE:
val1 will return the value of string_val before the searched value of #val (the LOCATE result need to have a deduction of 1).
val2 will return the value of string_val that matches #val and anything after it.
In the outer query, chk1 checks the last character extracted to val1 against alphabets using REGEXP. In this case GOBALL will return true (1) while 9232BALL and 9232BALLV will return false (0). Here we'll look at whatever false.
chk2 checks if val2 matches the searched #val. Therefore, the separated value of 9232BALL which end up getting BALL for val2 will return true (1) while 9232BALLV which end up getting BALLV for val2 will return false (0). Here we'll look at whatever is true.
The last filter is checking the addition of chk1+chk2. The result we're looking for is 1 because chk1 need to be false (0) and chk2 need to be true (1).
SELECT String_val AS 'Value',
CASE WHEN chk1+chk2=1 THEN 'Yes' ELSE 'No' END AS 'Yes/No'
FROM
(SELECT *,
RIGHT(val1,1) REGEXP '[a-zA-Z]' AS chk1,
val2=#val AS chk2
FROM
(SELECT string_val,
SUBSTRING(string_val,1,LOCATE(#val,string_val)-1) val1,
SUBSTRING(string_val,LOCATE(#val,string_val)) val2
FROM mytable) A) B
Alternative option 1:
SELECT string_val,
CASE WHEN
REGEXP_REPLACE(CASE WHEN val1 REGEXP '[a-zA-Z]$' = 1
THEN CONCAT(val1,val2) ELSE val2 END,'[0-9]','')=#Val
THEN 'Yes' ELSE 'No' END AS 'Yes/No'
FROM
(SELECT string_val,
SUBSTRING(string_val,1,LOCATE(#val,string_val)-1) val1,
SUBSTRING(string_val,LOCATE(#val,string_val)) val2
FROM mytable) A;
Alternative option 2:
My further testing shows that it's possible to get the result using REGEXP_SUBSTR with a much shorter query:
SET #val := 'BALL';
SELECT string_val,
REGEXP_SUBSTR(string_val, '[a-zA-Z]+[BALL]+[a-zA-Z]') AS vals,
IF(((SELECT vals))=#val,'YES','NO') AS 'Yes/No'
FROM mytable;
Demo

MySQL How to use and OR inside an AND operator for a where clause?

I'm trying to use AND with OR's inside my WHERE clause but I'm not getting expected results. This is my query:
select *
from Pitches
where BatterID = #playerID
and YEAR(GameDate) in (2019)
and (BattedBallID is not null or BattedBallID <> 0);
The problem is I'm getting BattedBallID's that have 0 in the rows but none of them have null. I want it so my results have BattedBallID's that aren't 0 and aren't null;
I want it so my results have BattedBallID's that aren't 0 and aren't null;
You want:
and BattedBallID is not null and BattedBallID <> 0;
Instead of:
and (BattedBallID is not null or BattedBallID <> 0);
Your original expression will actually always evaluate as true, since both conditions cannot be false at the same time : if something is null, then it is not equal to 0, and if something is equal to 0, then it is not null.

NULL != NULL in mysql query

I am trying to do a query that sees if fields are equivalent. However, whenever the field is NULL it returns a false result. I even tried doing the same thing with the column itself:
SELECT * FROM `mturk_completion` WHERE (`mturk_completion`.`imdb_url` =
`mturk_completion`.`imdb_url` AND `mturk_completion`.`worker_id` = 'A3NF84Q37D7F35' )
And it only returns results where the column is not NULL. Why is this so, and how do I get around it?
Your title is absolutely correct for any SQL implementation (not just MySQL). NULL is not equal to anything (including another NULL).
You need to use explicit IS NULL check or COALESCE() function (or its RDBMS-dependent alternatives) to set some default value in case of NULL.
Your comparison of mturk_completion.imdb_url to itself is redundant and should always return True, except when mturk_completion.imdb_urlis Null, in which case it will return Null.
That's because the operator = returns either True, False when comparisons can be made or Null, when either of the two operators is Null
Try this to illustrate the situation.
SELECT 1 = NULL; -- returns NULL
SELECT 1 != NULL; -- also return NULL
SELECT ISNULL(1 = NULL); -- returns 1
SELECT ISNULL(1 != NULL); -- returns 1
If you rewrite your query like below, your problems with ignoring NULLs will go away:
SELECT * FROM `mturk_completion` WHERE worker_id = 'A3NF84Q37D7F35'
I think you can use
(table.Field = table2.Field OR COALESCE(table.Field, table2.Field) IS NULL)

When loading a csv file file how can insert negitive values as 0 and keep positive values

While reading over the docs I cannot seem to get this correct. I want to use load file to insert a CSV into a premade table. If one of the values is negative i want it to insert as 0. If not I want to keep its original value. I think im on the right track but i dont know.
ignore 1 lines (#item_name, #product_desc, #quanity_total) set item = #item_name, desc = #product_desc, quanity = if(#quanity_total < 0 then 0 else #quanity_total);
This part of your LOAD DATA INFILE statement could be written as:
ignore 1 lines
(#item_name, #product_desc, #quanity_total)
set item = #item_name,
`desc` = #product_desc,
quanity = if(#quanity_total < 0, 0, #quanity_total);
or by removing two not needed variables as:
ignore 1 lines
(item, `desc`, #quanity_total)
set quanity = if(#quanity_total < 0, 0, #quanity_total);
The column name desc is a reserved word and got to be quoted with backticks.
The IF syntax is as follows:
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns
expr2; otherwise it returns expr3. IF() returns a numeric or string
value, depending on the context in which it is used.

why does sql = FALSE always return true

No matter what I do in MySQL 5.0 such as
SELECT 'test' = FALSE
SELECT '' = FALSE
I always get a 1 back in SQL. What is the reason for that? I was expecting a 0 or FALSE
EDIT adding context to the questions.
This is how the problem came about, it happened that $name inadvertently became false making this join always pass, then I wondered why this works.
SELECT a.id
FROM user a
INNER JOIN inventory b ON b.user_id = a.id AND b.name = $name
In MySql FALSE is a constant literal which is always evaluated as 0.
So you are checking if 'test' = 0 or if '' = 0, and since you are comparing a string with an integer, MySql will try to cast the string to an integer.
If you try this query:
SELECT 'test' = FALSE
it will return 1 (TRUE) because 'test' will be converted to 0, while if you try this:
SELECT '1test' = FALSE
it will return 0 (FALSE) because '1test' will be converted to 1.
This has to do with MySQL's implicit conversion when using comparison operators (i.e. =)
Taken from the docs:
Strings are automatically converted to numbers and numbers to strings as necessary.
So, in your case:
'test' gets converted to 0
FALSE is 0
0 = 0 is TRUE.