How to check if a field is null or empty mysql?

I am trying to figure out how to check if a field is null or empty. I have it

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

I need to add additional field1 != "" Something like

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

Any idea how to do this?

+59
sql mysql
Jul 24 '13 at 11:38
source share
6 answers

Or use

 SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename 

or

 SELECT case when field1 IS NULL or field1 = '' then 'empty' else field1 end as field1 from tablename 

If you only want to check for null and not empty lines, you can also use ifnull() or coalesce(field1, 'empty') . But this is not suitable for empty lines.

+134
Jul 24 '13 at 11:39 on
source share

Alternatively, you can also use CASE for this:

 SELECT CASE WHEN field1 IS NULL OR field1 = '' THEN 'empty' ELSE field1 END AS field1 FROM tablename. 
+10
Jul 24 '13 at 11:42 on
source share

You can create a function to facilitate its execution.

 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 
+2
Jan 20 '17 at 18:25
source share

You can use the IFNULL function inside 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 
+1
May 15 '18 at 14:05
source share

If you want to test PHP, you need to 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!"; } 
0
Nov 09 '13 at 0:17
source share
 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 
0
Dec 06 '16 at 11:13
source share



All Articles