Question

I have Query:

SELECT   Stage1
        ,Stage2
        ,Stage3 
FROM dbo.Cases
WHERE Number='6913'

result:

Stage1  Stage2      Stage3
==========================
NULL    Settlement  Stage1

But when i try:

SELECT COALESCE(Stage1 ,Stage2 ,Stage3) AS [Exit]
FROM   dbo.Cases
WHERE  Number = '6913'

result still NULL:

EXIT    
====
NULL

Why it is coming like this, result supposed to be 'Settlement'

Please anybody can help????

Was it helpful?

Solution

The only explanation I can think of for that is that you have the string value of NULL in your Stage1 field. See if this query returns your row to determine if that is the case:

SELECT   Stage1
        ,Stage2
        ,Stage3 
FROM dbo.Cases
WHERE Number='6913'
AND Stage1 = 'NULL'

If it is a string value of NULL you could try this:

SELECT   COALESCE(NULLIF(Stage1, 'NULL'), NULLIF(Stage2, 'NULL'), NULLIF(Stage3, 'NULL'))           
FROM dbo.Cases
WHERE Number='6913'

OTHER TIPS

Check that the value is an actual NULL and not the varchar value 'NULL'.

You can do this with:

SELECT * FROM dbo.Cases WHERE Stage1 IS NULL

SELECT * FROM dbo.Cases WHERE Stage1 = 'NULL'

And see what comes back.

There are a few other things you can do to remove NULLS.

Filter out nulls:

SELECT   Stage1
        ,Stage2
        ,Stage3 
FROM dbo.Cases
WHERE Number='6913'
  AND State1 IS NOT NULL

or place and empty string when Stage1 is null:

SELECT   ISNULL(Stage1, '')
        ,Stage2
        ,Stage3 
FROM dbo.Cases
WHERE Number='6913'

I have the same strange behavior. I think the problem is not with the COALESCE() function, but with the value in the attribute/column.

In my case, the value appears to be NULL, and the way the data flows, it should be NULL. However, neither the Postgres WHERE clause or the COALESCE() function interprets the value as NULL. I don't truly know what the value is.

My kluge solution is to take the MD5 hash of the value, and use the MD5 in my query logic. I don't truly know what the real/internal value of the attribute is, but we can calculate the MD5 hash and use it as a proxy.

, COALESCE(
          CASE WHEN md5(value1) <> 'd41d8cd98f00b204e9800998ecf8427e' THEN value1 ELSE NULL END
        , CASE WHEN md5(value2) <> 'd41d8cd98f00b204e9800998ecf8427e' THEN value2 ELSE NULL END
        , CASE WHEN md5(value3) <> 'd41d8cd98f00b204e9800998ecf8427e' THEN value3 ELSE NULL END
    ) AS desired_value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top