Standard SQL alternative to Oracle DECODE
Asked Answered
E

4

12

Is there an ANSI SQL equivalent to Oracle's DECODE function?

Oracle's decode function is the IF-THEN-ELSE construct in SQL.

Electronic answered 9/7, 2010 at 11:15 Comment(0)
S
22

A CASE expression is the ANSI SQL method, of which there are 2 varieties, "simple" and "searched":

1) Simple CASE expression:

CASE col WHEN 1 THEN 'One'
         WHEN 2 THEN 'Two'
         ELSE 'More'
         END

2) Searched CASE expression:

CASE WHEN col < 0 THEN 'Negative'
     WHEN col = 0 THEN 'Zero'
     ELSE 'Positive'
     END
Saari answered 9/7, 2010 at 11:23 Comment(0)
J
3
CASE WHEN a=1 THEN value1
     WHEN a=2 THEN value2
     ELSE default
END

SQL Case Statement Syntax?

Jehol answered 9/7, 2010 at 11:18 Comment(0)
P
3

Please note that Oracle DECODE treats null as equal to null, while CASE(and any other comparisons) don't.

Example: Decode(a,b,1,0) will return 1 if both a and b are nulls.

Just run these 2 statements to see the difference.

select case null when null then 'Y' else 'N' end dd from dual;
select decode(null, null, 'Y', 'N') dd from dual;
Papistry answered 9/10, 2018 at 9:13 Comment(1)
Note that case when <whatever> is null then has the expected behaviour whereas case <whatever> when null then doesn't, it's a famous pitfall.Spleenful
B
0

adding it up null can be compared in decode whereas in case it is not.

Backpack answered 9/10, 2018 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.