Monday, August 12, 2019

Difference between CASE and DECODE


Overview:

Decode fucntion and Case statement are very similar but CASE is an extended version of DECODE.
CASE is introduced in Oracle 9i version.

1) DECODE will return "TRUE" if you compare NULL to NULL.  CASE will not.
 For example 1): SELECT decode(null,null,1,0) from dual;
         Output: 1

             2) SELECT CASE NULL
                     WHEN NULL THEN 1
                     ELSE 0
                     END
                FROM DUAL;
         Output:  0

2) CASE is a statement and DECODE is a function.

3) We can use the CASE in the where clause and can not use the DECODE in the where clause.

4) DECODE can check equality operators only where as CASE can support all relational operators.

5) DECODE can be used in sql only where as CASE can be used in SQL AND PL/SQL.
   For example:
   --
   DECLARE
     grade char(1);
   BEGIN
      grade := 'b';
      CASE grade
          WHEN 'a' THEN dbms_output.put_line('excellent');
          WHEN 'b' THEN dbms_output.put_line('very good');
          WHEN 'c' THEN dbms_output.put_line('good');
          WHEN 'd' THEN dbms_output.put_line('fair');
          WHEN 'f' THEN dbms_output.put_line('poor');
        ELSE dbms_output.put_line('no such grade');
      END CASE;
   END;
   /
 
6) DECODE works with expressions that are scalar values only. CASE can work with predicates and subqueries in searchable form.

7) CASE can even work as a parameter to a procedure call, while DECODE cannot.

   exec proc_test(case :a when 'THREE' then 3 else 0 end);

8) In very simple situations, DECODE is shorter and easier to understand than CASE.

No comments:

Post a Comment

Steps to get ZPL code output using Zebra viewer - Online

Introduction ZPL is a print language used by many label printers. A print language is a set of commands that can be used to draw elements li...