Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

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?

like image 294
veereev Avatar asked Jul 24 '13 11:07

veereev


People also ask

Is NULL or empty in SQL?

NULL is used in SQL to indicate that a value doesn't exist in the database. It's not to be confused with an empty string or a zero value. While NULL indicates the absence of a value, the empty string and zero both represent actual values.

Is not null or empty SQL?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

IS NOT NULL in MySQL?

The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.


1 Answers

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.

like image 105
juergen d Avatar answered Sep 30 '22 11:09

juergen d