MySQL select where column is not empty

后端 未结 13 2158
深忆病人
深忆病人 2020-11-30 18:18

In MySQL, can I select columns only where something exists?

For example, I have the following query:

select phone, phone2
from jewishyellow.users
wh         


        
13条回答
  •  天涯浪人
    2020-11-30 18:34

    An answer that I've been using that has been working for me quite well that I didn't already see here (this question is very old, so it may have not worked then) is actually

    SELECT t.phone, 
           t.phone2 
      FROM jewishyellow.users t
     WHERE t.phone LIKE '813%' 
       AND t.phone2 > ''
    

    Notice the > '' part, which will check if the value is not null, and if the value isn't just whitespace or blank.

    Basically, if the field has something in it other than whitespace or NULL, it is true. It's also super short, so it's easy to write, and another plus over the COALESCE() and IFNULL() functions is that this is index friendly, since you're not comparing the output of a function on a field to anything.

    Test cases:

    SELECT if(NULL > '','true','false');-- false
    SELECT if('' > '','true','false');-- false
    SELECT if(' ' > '','true','false');-- false
    SELECT if('\n' > '','true','false');-- false
    SELECT if('\t' > '','true','false');-- false
    SELECT if('Yeet' > '','true','false');-- true
    

    UPDATE There is a caveat to this that I didn't expect, but numerical values that are zero or below are not greater than a blank string, so if you're dealing with numbers that can be zero or negative then DO NOT DO THIS, it bit me very recently and was very difficult to debug :(

    If you're using strings (char, varchar, text, etc.), then this will be perfectly be fine, just be careful with numerics.

提交回复
热议问题