[mysql] How to check if field is null or empty in MySQL?

I am trying to figure out how to check if a field is NULL or empty. I have this:

SELECT IFNULL(field1, 'empty') as field1 from tablename

I need to add an additional check field1 != "" something like:

SELECT IFNULL(field1, 'empty') OR field1 != ""  as field1 from tablename

Any idea how to accomplish this?

This question is related to mysql sql

The answer is


You can use the IFNULL function inside the IF. This will be a little shorter, and there will be fewer repetitions of the field name.

SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1 
FROM tablename

If you would like to check in PHP , then you should do something like :

$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
  //do your action
  echo "It was filled";
} else { 
  echo "it was empty!";
}

You can create a function to make this easy.

create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);

Using:

SELECT IFEMPTY(field1, 'empty') as field1 
from tablename

Alternatively you can also use CASE for the same:

SELECT CASE WHEN field1 IS NULL OR field1 = '' 
       THEN 'empty' 
       ELSE field1 END AS field1
FROM tablename.

SELECT * FROM ( 
    SELECT  2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'')  AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION 
    FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
    JOIN acc_head L ON(D.ACC_ID=L.ID) 
    JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)  
    WHERE T.CMPID=',COMPANYID,' AND  d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
    ORDER BY CAST(ENTDT AS DATE)) AS ta

Try using nullif:

SELECT ifnull(nullif(field1,''),'empty') AS field1
  FROM tablename;