SELECT IFNULL(NULL, 'Replaces the NULL') --> Replaces the NULL SELECT COALESCE(NULL, NULL, 'Replaces the NULL') --> Replaces the NULL
In both clauses the main difference is argument passing. For IFNULL
it's two parameters and for COALESCE
it's multiple parameters. So except that, do we have any other difference between these two?
And how it differs in MS SQL?
Comparing COALESCE and ISNULL Data type determination of the resulting expression is different. ISNULL uses the data type of the first parameter, COALESCE follows the CASE expression rules and returns the data type of value with the highest precedence.
advantage that COALESCE has over ISNULL is that it supports more than two inputs, whereas ISNULL supports only two. Another advantage of COALESCE is that it's a standard function (namely, defined by the ISO/ANSI SQL standards), whereas ISNULL is T-SQL–specific.
Mladen aka spirit1 posted a speed test of COALESCE vs. ISNULL. Reported result: COALESCE is faster.
The ISNULL and Coalesce functions are both used to replace null values with a user-defined value.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With