48 Votes

MySQL: How to check if Field is NULL or EMPTY

Question by Guest | 2015-06-10 at 17:28

Does someone know any way in MySQL to check whether an arbitrary field of a table is either containing an empty value (empty string) or it is NULL?

I have tried some things with IFNULL and similar approaches, but I had no success. Is there any trick? What should I take into account?

ReplyPositiveNegativeDateVotes
15Best Answer27 Votes

If you want to read out all data records from a table containing an empty string or NULL as value in one specific column, you can use the following query:

SELECT * FROM tab WHERE col IS NULL OR col = ''

With "IS NULL", you can check for NULL, with "= ''", you can check for an empty string.

If you are searching for all datasets where the field is not NULL and not empty, you can use the following query instead:

SELECT * FROM tab WHERE col IS NOT NULL AND col != ''

If you want to use an IF condition for it, you can write it like that, for example:

SELECT IF(col IS NULL OR col = '', 'empty', col) FROM tab

With this query, you are checking at each dataset whether "col" is NULL or empty and depending on the result of this condition, either the string "empty" is returned in the case that the condition is TRUE or the content of the column is returned if not.
2015-06-12 at 18:11

ReplyPositive Negative
-422 Votes

The following is more efficient for finding empty fields:

SELECT * FROM tab WHERE col > '';

2017-01-05 at 10:29

Positive Negative
-614 Votes

For "IF(col IS NULL OR col = '', 'empty', col)", I believe you could use COALESCE().
2017-06-01 at 00:47

Positive Negative
Reply
11 Vote

You can also use the IFNULL() function:

1. SELECT IFNULL(1,0); -- returns 1

2. SELECT IFNULL('',1); -- returns ''

3. SELECT IFNULL(NULL,'IFNULL function'); -- returns "IFNULL function"
2019-06-11 at 18:21

ReplyPositive Negative
Reply

Related Topics

Android Getting Sound Levels

Open Question | 1 Answer

MySQL: Check for NULL

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.