00 Votes

MySQL: Check for NULL

Question by Compi | Last update on 2021-05-13 | Created on 2015-07-08

I would like to check whether a field or the content of one field of a column is NULL with the help of MySQL.

For this, I have constructed the following query:

SELECT id, IFNULL(col, 0, col) FROM tab

This query should either read out the value of the column "col" in the case "col" is not NULL or 0 if it is NULL.

Unfortunately, the query is not working in this way. I always get the following error message:

#1582 - Incorrect parameter count in the call to native function 'IFNULL'

Can someone tell me how to rewrite this database query so that it is properly working? As far as I know, the normal IF is expecting 3 parameters, so, what am I doing wrong here?

ReplyPositiveNegative
0Best Answer0 Votes

There are two possibilities you can use to change your query.

Either you can write

SELECT id, IF(col IS NULL, 0, col) FROM tab

or you can change your query to:

SELECT id, IFNULL(col, 0) FROM tab

The first query is using the normal IF of MySQL. As first parameter, you specify "col IS NULL", with which you check whether "col" is NULL. Accordingly, as second and third parameter, you can specify what should be returned depending on the condition. That is 0 if the condition is TRUE ("col" is NULL) or the content of "col" in the case that the condition is FALSE ("col" is not NULL).

The second example shows how to use IFNULL correctly. IFNULL expects two parameters: First the value to be checked (in your case the content of "col") and as a second parameter the value that should be returned if the first parameter is NULL. Otherwise, the first parameter is returned.

Of course, the first way always has an advantage whenever you do not want to just read out the content of the corresponding column, for example if you would like to return any alternative content or if you would like to modify the original content of the column.
Last update on 2021-05-13 | Created on 2015-07-08

ReplyPositive Negative
Reply

Related Topics

Android Getting Sound Levels

Open 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.