tags:

views:

126

answers:

1

I'm working on maintaining some Oracle sql statements written by someone else, and all over the place I keep seeing this same pattern repeated in lots of statements and pl/sql blocks:

select DECODE(NVL(t1.some_column,'~'),'~',t2.some_column,t1.some_column) some_column from t1, t2 where ...

Now, isn't this identical to this much simpler statement?

select NVL(t1.some_column,t2.some_column) from t1, t2 where...

I'm not sure why the decode and nvl are being chained in the original query. It seems like a less efficient way of just doing nvl alone. Can someone explain this to me?

Thanks for any insight!

+4  A: 

Wow, um, looks like pretty poor coding there.

NVL(t1.some_column, t2.some_column)

...gives the same results.

I'm more comfortable with COALESCE, though:

COALESCE(t1.some_column, t2.some_column)

That way, if you ever want to add on a third, it's just:

COALESCE(t1.some_column, t2.some_column, t3.some_column)

It appears that whoever wrote the original code wanted it to be extendible and just didn't know about COALESCE...

Eric
Thanks for the quick reply. I just needed that sanity check... I didn't think my sql skills were that bad, but the original decode(nvl()) magic has passed through the hands of 2 DBAs (which I am not), so I wasn't sure.
rally25rs
Oh and thanks for the heads-up on the COALESCE function. I hadn't seen that one before... I'll add it to my toolbelt :)
rally25rs
Well...you know, sometimes people see something that works and they don't wanna touch it. Sadly.
Eric
It depends. Does t1.some_column ever actually contain the string '~' ?If so, then the original decode will return t2.some_column whereas the simpler solutions will return '~'.
Gary
Gary is correct. I immediately thought of `~` being nothing more than an arbitrary character. You don't have any `~` values, do you?
Eric
No. I actually think '~' was chosen because its not valid. I also believe a lot of the time the column being nvl'd is actually a number anyway, not varchar.
rally25rs