2

I have a table with 3 columns: c1, c2 and c3. I want to write a select statement so that if both c1 and c2 are null, display c3, otherwise display c1.

What would be the best way to write a select statement in the above scenario?

0

1 Answer 1

8

Using CASE

CASE WHEN C1 IS NULL AND C2 IS NULL
     THEN C3
     ELSE C1
END

Using NVL2

NVL2(C1,C1,NVL2(C2,C1,C3))

OR

NVL2(C1||C2,C1,C3)

Using DECODE

DECODE(C1,NULL,DECODE(C2,NULL,C3,C1),C1)

Readability and ease wise CASE wins.

Sign up to request clarification or add additional context in comments.

7 Comments

One of my colleagues had written like this. Is this a good way to handle this scenario? select nvl2(c1||c2, c1, c3) from XXX
No it is wrong, if either c1 or c2 is null, c3 is returned in that expression, since concatenating any string with NULL gives NULL only, but we should always handle NULL before hand.As you dont know, which one was NULl, either c1 or c2.. also CASE would be everyone's choice.
I've tried my colleague's select statement in Oracle 11g and found that concating null string with another string literal will return the literal itself. So my colleague's solution works even though I also feel that "Case When" is a better solution.
Oracle is known to have a buggy NULL vs. '' (empty string) implementation. It treats both the same, usually but not always like NULL, e.g. TRANSLATE('jhkhkxhkx', 'x', '') will not work, you need TRANSLATE('jhkhkxhkx', '.x', '.') instead
It's not buggy, it's intended @dnoeth and the behaviour of TRANSLATE() is well documented, so I don't see how you can call this buggy either.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.