0

This question seems really basic, but I cant find the answer by google, and I've spent the last hour testing with no luck. Im having difficulties trying to return a set of rows. I want the rows that equal 11, 1, or Null. I think it is Null that is messing me up. Below is just one of the many tests I ran...and I know it doesn't work. Any help is REALLY appreciated. Thanks in advance

SELECT * FROM have
    WHERE have.flag = 11 || 1 || NULL;

4 Answers 4

4

You will need to treat NULL separately from 1 and 11, then just put the values into your where clause.

SELECT *
FROM have AS h
WHERE h.flag IS NULL
   OR h.flag IN (1, 11);
Sign up to request clarification or add additional context in comments.

3 Comments

Actually, || does mean logical-OR in MySQL: dev.mysql.com/doc/refman/5.5/en/…
@muistooshort Thanks for the reference on ||, hadn't seen that before.
MySQL makes you use the CONCAT function for string concatenation, sigh.
1

Just as an alternative:

SELECT *
FROM   have
WHERE  nullif(nullif(flag,1),11) IS NULL

2 Comments

Doesn't the function against the column negate the ability to use any index for the WHERE criteria?
That's generally true, assuming there is an index. Not sure how MySQL handles indexes, but Postgres allows you to index functions. Still, I'd go with Adam's answer for the clarity and that reason, even if the question didn't specify. -- I only meant for this answer to be an educational alternative.
1

Alternatively, you could go for

select * from have as h where
IFNULL(h.flag,1) in (1,11)

4 Comments

You should change the first 11 to a 1, for less characters :)
@vol7ron I didn't see that. Thanks!
It's not going to make or break anything. Also the have_flag can be changed to just flag
Doesn't the function against the column negate the ability to use any index for the WHERE criteria?
1

This is the explanation:

SELECT * FROM have
    WHERE have.flag = 11 || 1 || NULL;

What you are stating is actually:

(have.flag = 11) || 1       || NULL
true || 1                   || NULL
1                           || NULL
1


(have.flag = 11) || 1       || NULL
false || 1                  || NULL
1                           || NULL
1

It will always evaluate to 1.
= has higher precedence than ||.
@Adam Wenger's answer is correct.

1 Comment

True. Even in the simplest of cases, the query should be WHERE have.flag = 1 || have.flag = 11 || have.flag IS NULL. The column should be in each condition in the WHERE criteria.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.