From the course: Complete Guide to Advanced SQL Server

Unlock the full course today

Join today to access over 24,700 courses taught by industry experts.

Merge rows with COALESCE

Merge rows with COALESCE

The COALESCE function provides another useful way for working with and replacing null values that occur within your data. It takes a slightly different approach from the ISNULL function that we just looked at. ISNULL, you recall, takes a pair of parameters. The first parameter is evaluated, and if it returns a null, then the second parameter is returned instead. COALESCE, on the other hand, only takes expression parameters, but it can take a whole lot of them. One expression, two expressions, three expressions. As many as you want. The function will look at each expression in sequence, and it'll return the first one that is not null. So if we apply it to the function here; COALESCE (NULL, NULL, 'kangaroo', 'elephant') If I execute this, it returns 'kangaroo'. The first non-null value. If we pass it for null functions by running Line Number 12 here, well, this time we get an error. That's because SQL Server requires at least one non-null constant. This means we need to either provide a…

Contents