51

How does one detect whether a field is blank (not null) and then select another field if it is?

What I really need is a IsBlank function that works the same as IsNull but with with blanks.

REPLACE doesn't work with blanks, COALESCE only works with NULLS.

4 Answers 4

122

How about combining COALESCE and NULLIF.

SELECT COALESCE(NULLIF(SomeColumn,''), ReplacementColumn)
FROM SomeTable
4
  • Interesting...can it be easily extended to work with 3 columns? Nov 17, 2009 at 14:49
  • 8
    Answer - yes you can: COALESCE(NULLIF(Address2,''), NULLIF(Address3,''), Address4) Nov 17, 2009 at 14:51
  • Moving the answer to yours as it is more elegant than the Case statement. Nov 17, 2009 at 14:52
  • 1
    It is unreal how much this helped me.
    – Angesehen
    Aug 21, 2019 at 18:09
19

You can use a CASE statement for this

select 
Case WHEN Column1 = '' OR Column1 IS NULL OR LEN (TRIM (Column1))  = 0 
     THEN Column2 
     ELSE Column1 END as ColumnName
from TableName
2
  • 1
    This is what I had got on my own but is very ungainly. Nov 17, 2009 at 10:13
  • I tried that but was somehow getting duplicate rows added. Oct 30, 2019 at 21:25
5

EDIT: You can't use IF() in mssql.

Use an IF statement in the SELECT portion of your SQL:

SELECT IF(field1 != '', field1, field2) AS myfield FROM ...
3
  • Nice, but if I need to work more than 2 columns will be a pain. Nov 17, 2009 at 10:14
  • 1
    I can't seem to get it working: SELECT IF(Address2!='', Address2, Address3) AS Address FROM Sites gives Incorrect syntax near the keyword 'IF'. Nov 17, 2009 at 10:20
  • 2
    Okay, I'm a total dumbass and getting confused with mysql. IF() only seems to work with mysql, so rather use CASE WHEN THEN ELSE END as above. I'll leave this here as a warning to others :)
    – MDCore
    Nov 17, 2009 at 11:31
2

You could always write an isBlank() function, something like

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION isBlank
(
    @CheckExpression varchar, @ReplacementExpression varchar
)
RETURNS varchar
AS
BEGIN
    IF @CheckExpression IS NOT NULL
    BEGIN
        IF @CheckExpression='' or LEN(@CheckExpression) = 0
        RETURN @ReplacementExpression
    ELSE
        RETURN @CheckExpression
    END

    RETURN @ReplacementExpression
END
GO
1
  • I assume you could make it support N number of expressions since COALESCE does anyway via case statement like Raj More. Nov 17, 2009 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.