The main difference between the two is that IFNULL
function takes two arguments and returns the first one if it's not NULL
or the second if the first one is NULL
.
COALESCE
function can take two or more parameters and returns the first non-NULL parameter, or NULL
if all parameters are null, for example:
SELECT IFNULL('some value', 'some other value');
-> returns 'some value'
SELECT IFNULL(NULL,'some other value');
-> returns 'some other value'
SELECT COALESCE(NULL, 'some other value');
-> returns 'some other value' - equivalent of the IFNULL function
SELECT COALESCE(NULL, 'some value', 'some other value');
-> returns 'some value'
SELECT COALESCE(NULL, NULL, NULL, NULL, 'first non-null value');
-> returns 'first non-null value'
UPDATE: MSSQL does stricter type and parameter checking. Further, it doesn't have IFNULL
function but instead ISNULL
function, which needs to know the types of the arguments. Therefore:
SELECT ISNULL(NULL, NULL);
-> results in an error
SELECT ISNULL(NULL, CAST(NULL as VARCHAR));
-> returns NULL
Also COALESCE
function in MSSQL requires at least one parameter to be non-null, therefore:
SELECT COALESCE(NULL, NULL, NULL, NULL, NULL);
-> results in an error
SELECT COALESCE(NULL, NULL, NULL, NULL, 'first non-null value');
-> returns 'first non-null value'
IFNULL
checks a single argument.COALESCE
works with N arguments.COALESCE
is useful when you have unknown number of values that you want to check.IFNULL
is useful when you select columns and know that it can be null but you want to represent it with a different value. Therefore, the two functions are vastly different. As for MSSQL difference - google can help you, you can obtain this information much quickly by doing your own research. – ExterminateIFNULL
checks a single argument.COALESCE
works withN
arguments. ", for the case whereN = 2
, both works. Which will you use then? – Sanson