Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference bewteen ifnull and coalesce in mysql?

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?

like image 334
shree18 Avatar asked Aug 30 '13 08:08

shree18


People also ask

What is the difference between Isnull and coalesce?

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.

Which is better Isnull or coalesce?

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.

Which is faster coalesce or Isnull?

Mladen aka spirit1 posted a speed test of COALESCE vs. ISNULL. Reported result: COALESCE is faster.

Can you use user-defined type in Isnull () or coalesce ()?

The ISNULL and Coalesce functions are both used to replace null values with a user-defined value.


1 Answers

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' 
like image 97
Aleks G Avatar answered Sep 21 '22 13:09

Aleks G