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

Either 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 for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.


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

Try using nullif:

SELECT ifnull(nullif(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.

Tags:

Mysql

Sql