I have used COALESCE numerous times but I suppose I never encountered this particular situation. Assume there is only one row per @param1.
select @test = COALESCE (column1, 'default') FROM Table1 WHERE column3 = @param1
In this scenario, if the value of column1 is null, 'default' is selected when the sql statement actually returns a row. What if there are no matching records for @param1.
Lets say I want to always have a default value for @test. Is the following correct or is there another way?
select @test = COALESCE( (select column1 FROM Table1 WHERE column3 = @param1), 'default').
I presumed that, select @test = COALESCE (column1, 'default') FROM Table1 WHERE column3 = @param1
, will contain 'default' even if it did not return a row. Nope.
I suppose I can also check if @test is NULL afterwards and assign a default value as well.
COALESCE does not work with empty strings as documentation states it would · Issue #9416 · apache/druid · GitHub.
The SQL server's Coalesce function is used to handle the Null values. The null values are replaced with user-defined values during the expression evaluation process. This function evaluates arguments in a particular order from the provided arguments list and always returns the first non-null value.
The COALESCE function returns the first non-NULL value from a series of expressions. The expressions are evaluated in the order in which they are specified, and the result of the function is the first value that is not null. The result of the COALESCE function returns NULL only if all the arguments are null.
COALESCE and ISNULLadvantage 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.
You already effectively mentioned the answer... Use COALESCE
after/outside the SELECT, as otherwise you never actually assign a value (which is different from assigning a NULL value)...
SELECT @test = NULL
SELECT @test = column1 FROM Table1 WHERE column3 = @param1
SELECT @test = COALESCE(@test, 'default')
Or simply...
SELECT @test = COALESCE((SELECT column1 FROM Table1 WHERE column3 = @param1), 'default')
You could also just give the variable the default value at declaration. If no rows are returned by the query no assignment will be made.
DECLARE @test VARCHAR(10) = 'default'
SELECT @test = COALESCE(column1, @test) /*Might not need COALESCE
if column1 is not nullable*/
FROM Table1
WHERE column3 = @param1
SELECT @test
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