Decode in pl/sql

Hi all
I read that in order to use the DECODE function in PL/SQL block you will have to use the system table dual.
my query is why we cannot use user table like emp while using decode function???

thois might give some help,
in general use dual, if the function used in the select list is independent of any data of a particular table, like emp in your case, check this out,
select decode('',null,'is null','is not null') from dual
will return is null
but
select decode('',null,'is null',' is not null') from emp
will work and will give the same result but will give many records as of emp table, so either a distinct can be used or row_num = 1 can be used, but the whole point to to get things done with little cost, so better use dual for such tables...
answering this query, i have got few doubts, decode() is a fuunction which does the selection operation, but
1) how to implement a custom function with variable number of parameters
2) as decode is a function which returns one of the input parameter on execution, why can't we call
x := decode('',null,'is null','is not null');
kindly reply to the above two queries???
cheere

Similar Messages

  • Using DECODE Function in SQL

    I need to know if there is any way to use a range of values from
    database and decode to certain text. I am able to do with one
    value.
    for example:
    DECODE(column_name,'216767111','Unlimited',column_name)
    above argument works with one value only. How about a range,
    ex: 216767000 to 216767111. I need to use only SQL. No PL/SQL.
    Kinldly need some body's help
    Thanks
    Munis

    Which version of the database? If it's 8i+ then you can use
    the CASE function
    for example:
    (CASE WHEN column_name between 216767000 and 216767111
    THEN 'Unlimited' ELSE column_name END)
    This won't work in PL/SQL because they're introducing a CASE
    statement does soemthing different.
    rgds, APCHello Andrew
    Thank you for response. I am using 8i. 8.1.6. However using
    CASE, I get inconsistent data type, ORA-00932: inconsistent
    datatypes. I able to work it out with other response using
    DECODE(sign(. Do you have any idea why i am getting this error.
    If time permits, let me know

  • Decode help in sql

    i m writing an sql query to print records
    select role_name,date_created,date_modified,createdbyuser_id,modifiedbyuser_id from t_role;
    This returns me the the rows in table t_role.
    But what i want is instead of the id of the person being printed in createdbyuser_id and modifiedbyuser_id, it shud provide me the username from another table user by checking the user_id field of table user.For this i used the fuction decode .But it oesnt work
    select role_name,date_created,date_modified,(select user_name from user where user_id=createdbyuser_id),(select user_name from user where user_id=modifiededbyuser_id) from role;
    kindly point out the mistake.
    Shefali

    <<
    i m writing an sql query to print records
    >>
    and
    <<
    1) tried this
    select a.role_name,a.date_created, a.date_modified, b.user_name, c.user_name from role a, user b, user c where b.user_Id = a.createdbyuser_Id and c.user_Id = a.modifiedbyuser_Id;
    But getting this error::
    ORA-20001: Your query contains duplicate alias names, queries used for reports require unique alias names.
    Error saving column settings
    >>
    so you are working with report writer ?
    the error message is telling you all you need.
    just change :
    select  a.role_name ,a.date_created, a.date_modified
          , b.user_name, c.user_name
      from  role a, user b, user c
    where b.user_Id = a.createdbyuser_Id
       and c.user_Id = a.modifiedbyuser_Id
    ;to
    select  a.role_name ,a.date_created, a.date_modified
          , b.user_name_creator, c.user_name_modifier
      from  role a, user b, user c
    where b.user_Id = a.createdbyuser_Id
       and c.user_Id = a.modifiedbyuser_Id
    ;

  • DECODE works in SQL but not in a CURSOR

    I have simplified my problem to "DUAL":
    While in a SQL session :
    select decode(
    (select 1 from dual)
    ,(select 1 from dual)
    ,1
    ,0)
    from dual;
    Expected result: 1;
    Actual result: 1;
    Place this code in a PL/SQL block :
    declare
    X number;
    begin
    SELECT decode(
    (select 1 from dual)
    ,(select 1 from dual)
    ,1
    ,0)
    INTO X;
    FROM dual;
    end;
    Expected Result: X=1;
    Actual Result: ORA-06550 & PLS-00103 "Encountered the symbol SELECT".
    My Question:
    Why can't I place a select within a decode while in a PL/SQL block? I have also tried this in an Explicit cursor.

    This is another of those cases when the PL/SQL engine does not support a feature/syntax of the SQL engine. To do this in PL/SQL, execute it as dynamic SQL (which uses the SQL engine):
    declare
    X number;
    begin
      execute immediate
        'SELECT decode((select 1 from dual),' ||
                      '(select 1 from dual),1,0) ' ||
        '  FROM dual' into x;
      dbms_output.put_line( x );
    end;

  • Decode help in SQL function

    Hi,
    I'm writing an HTMLDB application that we will be using to track the number of hours that we put into a project (all projects), and I've got a routine that returns the number of hours that are possible within a given month M-F 8 hours a day. I use this value returned to indicate how many hours have been enterered.
    SELECT null link, 'Still Unrecorded' itsrdescr,trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
    WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END) hoursworked
    from dual
    UNION
    SELECT null link, wd.itsrdescr,sum(b.hoursworked) hoursworked
    FROM workdetail wd, breakdowns b
    WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END
    GROUP by wd.itsrdescr
    ORDER by hoursworked desc
    What I'm wanting is something along the lines of this:
    SELECT null link, 'Still Unrecorded' itsrdescr,decode((trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
    WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END)),<0,0,?????????) hoursworked
    from dual
    UNION
    SELECT null link, wd.itsrdescr,sum(b.hoursworked) hoursworked
    FROM workdetail wd, breakdowns b
    WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END
    GROUP by wd.itsrdescr
    ORDER by hoursworked desc
    which will include a decode statement to let me know when the value getting returned into hoursworked on that first column is less than zero which throws off the chart. In this particular case, it has a value of -6 which makes all my percentages go haywire. How would one code this statement to include a decode statement to find out if that sum is returning a negative number?
    Hope this made sense,
    TIA,
    cliff

    Hey Tyler,
    Actually.... It kinda killed the server. I'm trying to figure out a way to get the following functionality in a different way. Here is the way that the query turned out using the case statement.
    SELECT null link, '<b><font color="red">Still Unrecorded</font></b>' itsrdescr,
    (case
    when (trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
    WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END)) < 0 then 0
    else
    (trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
    WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END))
    end) hoursworked
    from dual
    UNION
    SELECT null link, wd.itsrdescr,sum(b.hoursworked) hoursworked
    FROM workdetail wd, breakdowns b
    WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END
    GROUP by wd.itsrdescr
    ORDER by hoursworked desc
    Any tips on what I could do to get the above functionality without killing my server.
    Thx for the input
    cliff

  • SQL*LOADER and decode

    I'm setting up a sql*loader script and trying to use the decode function as referred to in 'Applying SQL Operators to Fields' I'm getting an error message ' Token longer than max allowable length of 258 chars'. Is there a limit to the size of the decode statement within sql*loader - or is it better to use a table trigger to handle this on insert? I ran the decode statement as a select through SQL*Plus and it works okay there. Oracle 8.0 Utilities shows example of decode in Ch. 5, but Oracle 9i Utilities Ch. 6 does not. Has anyone done this and what's the impact on performance of the load if I can get it to work? See my example below:
    LOAD DATA
    INFILE 'e2e_prod_cust_profile.csv'
    APPEND
    INTO TABLE APPS.RA_CUSTOMER_PROFILES_INTERFACE
    FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'
    (Insert_update_flag CHAR(1),
    Orig_system_customer_ref CHAR(240),
    customer_profile_class_name CHAR(30) NULLIF customer_profile_class=BLANKS
    "decode(customer_profile_class_name,
    'NORTHLAND Default','(MIA) Default',
    'NORTHLAND Non Consolidated','(MIA) Non Cons',
    'NORTHLAND Consolidated A','(MIA) Cons A',
    'NORTHLAND Consolidated B','(MIA) Cons B',
    'NORTHLAND Consolidated C','(MIA) Cons C',
    'NORTHLAND Consolidated D','(MIA) Cons D',
    'NORTHLAND Cons A NonZS','(MIA) Cons A NonZS',
    'NORTHLAND Cons B NonZS','(MIA) Cons B NonZS',
    'NORTHLAND Cons C NonZS','(MIA) Cons C NonZS',
    'NORTHLAND Cons D NonZS','(MIA) Cons D NonZS',
    'NORTHLAND International Billing','(MIA) International Billing',
    customer_profile_class_name)",
    credit_hold CHAR(1),
    overall_credit_limit INTERGER EXTERNAL,
    "e2e_cust_profile.ctl" 49 lines, 1855 characters
    SQL*Loader-350: Syntax error at line 15.
    Token longer than max allowable length of 258 chars
    'NORTHLAND Consolidated D','(MIA) Cons D',
    ^

    Your controlfile is incomplete and has some typos, but you could try something like:
    create or replace function decode_profile_class_name (p_longname IN VARCHAR2)
    return VARCHAR2
    is
    begin
      CASE p_longname
        WHEN 'NORTHLAND Default'               THEN RETURN '(MIA) Default';
        WHEN 'NORTHLAND Non Consolidated'      THEN RETURN '(MIA) Non Cons';
        WHEN 'NORTHLAND Consolidated A'        THEN RETURN '(MIA) Cons A';
        WHEN 'NORTHLAND Consolidated B'        THEN RETURN '(MIA) Cons B';
        WHEN 'NORTHLAND Consolidated C'        THEN RETURN '(MIA) Cons C';
        WHEN 'NORTHLAND Consolidated D'        THEN RETURN '(MIA) Cons D';
        WHEN 'NORTHLAND Cons A NonZS'          THEN RETURN '(MIA) Cons A NonZS';
        WHEN 'NORTHLAND Cons B NonZS'          THEN RETURN '(MIA) Cons B NonZS';
        WHEN 'NORTHLAND Cons C NonZS'          THEN RETURN '(MIA) Cons C NonZS';
        WHEN 'NORTHLAND Cons D NonZS'          THEN RETURN '(MIA) Cons D NonZS';
        WHEN 'NORTHLAND International Billing' THEN RETURN '(MIA) International Billing';
        ELSE RETURN p_longname;
      END CASE;
    end;
    LOAD DATA
    INFILE 'e2e_prod_cust_profile.csv'
    APPEND
    INTO TABLE APPS.RA_CUSTOMER_PROFILES_INTERFACE
    FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'
    Insert_update_flag          CHAR(1),
    Orig_system_customer_ref    CHAR(240),
    customer_profile_class_name CHAR(30) NULLIF customer_profile_class=BLANKS "decode_profile_class_name(:customer_profile_class_name)"
    credit_hold                 CHAR(1),
    overall_credit_limit        INTEGER EXTERNAL

  • Function or pseudo-column 'DECODE' may be used inside a SQL statement only

    Hi everyone!
    I got the error in the subject concernig the follow piece of sql code
    + v_str_sql_body :=
    v_str_sql_body || ' and cod_entita ='
    || decode(cur.cod_entita_a,str_all,cur_ent.cod_entita,cur.cod_entita_a);
    execute immediate v_str_sql_body; +
    I can't understand what's the problem with it.
    Can anyone help me to find the error?
    Thank you in advance!
    Samuel
    Edited by: 996508 on 27-mar-2013 5.29

    Hi, Samuel,
    Welcome to the forum!
    996508 wrote:
    Hi everyone!
    I got the error in the subject concernig the follow piece of sql code
    + v_str_sql_body :=
    v_str_sql_body || ' and cod_entita ='
    || decode(cur.cod_entita_a,str_all,cur_ent.cod_entita,cur.cod_entita_a);
    execute immediate v_str_sql_body; +
    I can't understand what's the problem with it.Sorry, I can't understand what you're trying to do.
    Whenever you have a problem, post a complete script that people can run to re-create the problem and test their ideas. Include your complete PL/SQL code (if the problem involves PL/SQL) including code to call your procedure, a little sample data (CREATE TABLE and INSERT statements) for any tables involved, and the results you want the given sample data.
    Always say which version of Oracle you have (e.g., 11.2.0.3.0).
    See the forum FAQ {message:id=9360003}
    Can anyone help me to find the error?As the error message says, you can only use DECODE in a SQL statement. That is:
    v_str_body := v_str_body
            || ' and cod_entita = '
            || DECODE (...);is always an error, no matter what ... stands for.
    Perhaps you meant to have the DECODE inside the string literal.
    If not, then (depending on your version) you can use CASE instead of DECODE:
    v_str_body := v_str_body
            || ' and cod_entita = '
            || CASE  cur.cod_entita_a
                     WHEN  str_all  THEN  cur_ent.cod_entita
                                 ELSE  cur.cod_entita_a
               END;Anything that DECODE can do, CASE can do, too.
    DECODE is sometimes a little simpler than CASE to use, but only a little. It is never faster than CASE.
    CASE is sometimes much, much simpler to use than DECODE, and sometimes much faster, too.
    I won't say never use DECODE; but I will say rarely use DECODE. Use CASE instead, unless you have a specific reason why DECODE is better in that particular situation.
    In PL/SQL, you can also use IF ... THEN ... ELSE in places where you might want to use DECODE or CASE.
    For example:
    v_str_body := v_str_body
            || ' and cod_entita = ';
    IF  cur.cod_entita_a = str_all
    THEN
        v_str_body := v_str_body
                    || cur_ent.cod_entita;
    ELSE
        v_str_body := v_str_body
                    || cur.cod_entita_a;
    END IF;Edited by: Frank Kulash on Mar 27, 2013 5:59 PM
    Added IF ... THEN ... ELSE example.

  • Want to convert function in SQL Server 2000

    Hi ,
    i am writing this function in oracle.Could you please convert this function in SQL Server 2000 because i am new in this and dont know how to use decode function in sql.
    Please following is the code for oracle.
    CREATE OR REPLACE function fun ( localex varchar2,titlex varchar2)
    return number
    as  x number;
    begin
    select sum ( decode (count (username),max(prereq_count),1,0) ) x into x from
       SELECT
                       prereq_count,
                       username
                 FROM
                         table1
    group by     username ;
    return x;
    end fun;
    Regards
    Vishal

    Just take a look example below might give you idea :
    create or replace function f_makeAddress_tx (
    i_address_tx VARCHAR2,
    i_city_tx VARCHAR2,
    i_state_tx VARCHAR2,
    i_zip_tx VARCHAR2)
    return VARCHAR2
    is
    e_badZip EXCEPTION; u279E8
    pragma EXCEPTION_init(e_badZip,-20998); u279E9
    v_out_tx VARCHAR2(256);
    begin
    p_validateZip (i_zip_tx); u279E12
    v_out_tx:= i_address_tx||u2019, u2018|| u279E13
    i_city_tx ||u2019, u2018||
    i_state_tx ||u2019, u2018||
    i_zip_tx;
    return v_out_tx; u279E17
    exception
    when e_badZip then u279E19
    return i_zip_tx || u2018: Invalid zip code.u2019;
    end;
    Regards,
    Clint

  • Applying decode function in obiee 11g

    DECODE(A.AC_CCY,'INR',DECODE(DRCR_IND,'D',-1,1)*A.LCY_AMOUNT,DECODE(DRCR_IND,'D',-1,1)*A.FCY_AMOUNT),
    DECODE(DRCR_IND,'D',-1,1)*A.LCY_AMOUNT,
    Can any one help me how to decode the above sql statement in obiee 11g.
    Edited by: 925104 on Apr 3, 2012 12:48 AM

    you can achieve it by using CASE WHEN condition END function in obiee. nested case also supported by obiee.
    check the below link Decode Join  Condition in OBIEE RPD
    Thanks
    Jay.
    Edited by: Jay on Apr 3, 2012 12:56 PM

  • Decode

    Hello,
    Below is a query To note number of employees hired by year...If I want the format to look like
    No of employees (Total) Hired in 1996 Hired in 1997 Hired in 1998 Hired in 1999
    XXX 10 28 23 18
    What is the best approach if I was to use Decode function?
    SQL>select to_char(hire_date,'YYYY') "Hire-Date",count(*) "Number of Employees"
    from employees
    group by to_char(hire_date,'YYYY')
    having to_char(hire_date,'YYYY') in (1996,1997,1998,1999)
    Hire-Date Number of Employees
    1997 28
    1999 18
    1996 10
    1998 23

    user8479432 wrote:
    Hello,
    Below is a query To note number of employees hired by year...If I want the format to look like
    No of employees (Total) Hired in 1996 Hired in 1997 Hired in 1998 Hired in 1999
    XXX 10 28 23 18
    What is the best approach if I was to use Decode function? The generic term for that is Pivot . The FAQ of this forum has several good links:
    SQL and PL/SQL FAQ
    If you're using Oracle 10 (or earlier) then CASE (or DECOCDE, ir you prefer it) is the best way. Starting in Oracle 11.1, use SELECT ... PIVOT instead.
    SQL>select to_char(hire_date,'YYYY') "Hire-Date",count(*) "Number of Employees"
    from employees
    group by to_char(hire_date,'YYYY')
    having to_char(hire_date,'YYYY') in (1996,1997,1998,1999)
    /Not that you asked, but if you have a choice of filtering in the WHERE clause or the HAVING clause, the WHERE clause will always be more efficient. It would probably be a lot faster if you said something like
    WHERE   hire_date  >= DATE '1996-01-01'
    AND     hire_date  <  DATE '2000-01-01'especailly if you have an index on hire_date.

  • Using Decode in Expression Builder...

    Hi everybody,
    I want to use the DECODE function of SQL in an Expression Builder....
    Of course this function does not exist in any of the transformation categories(arithmetic,character,e.t.c.) in the expression builder.
    I have read in the OWB on-line help that in the Expression Builder there should be an 'Others' drop - down list in order to select any of the available SQL clauses - one of them is 'decode'...
    The problem is that this drop - down list in the Expression Builder is disabled.....
    How can I use this function anyway..????
    Instead of using ... in the Expression Builder...
    decode(<column_name>,'1','val_one','2','val_two') what can I use to do the same....???
    As regards the problem that the drop-down list is disabled , what may be the cause..???
    I use Microsoft XP machine , Oracle 10g (v.10.2) and OWB v.10.1.0.4
    The documentation says....
    "This allows you to deploy the DECODE functionality in all operating modes (setbased, rowbased, etc.) and transparently across Oracle database releases (8.1, 9.0 and 9.2)."
    The above means that the cause is the incompatibility..????
    Thanks , a lot
    Simon

    I am using OWB 9.2.0.8 and I can't reproduce the problem you are having with 10.1, but did you try just typing it into the expression?
    Or, better yet, use CASE. The syntax is easier to read. I think OWB translates DECODEs to CASE when the SQL is generated.
    (Case <column_name>
       When '1' Then 'val_one'
       When '2' Then 'val_two'
    End)

  • Sql loader issue

    Hi I am trying to use decode function with sql loader.. and gating error
    SQL*Loader-350: Syntax error at line 8.
    Expecting "," or ")", found keyword nullif.
    code(:error_type,'Banned SBI',:error_type)" NULLIF error_type=BLANKS,
    My ctl file is below...
    LOAD DATA
    INFILE 'abc.dat'
    BADFILE 'abc.bad'
    INTO TABLE xyz_tmp
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    TRAILING NULLCOLS
    (record_id INTEGER EXTERNAL(4) NULLIF record_id=BLANKS,
    error_type CHAR(100) "decode(:error_type,'Banned',:error_type)" NULLIF error_type=BLANKS,
    error_subtype CHAR(100) NULLIF error_subtype=BLANKS,
    number_of_errors INTEGER EXTERNAL(3) NULLIF number_of_errors=BLANKS,
    sbi_number INTEGER EXTERNAL(8) NULLIF sbi_number=BLANKS,
    team_name CHAR(60) NULLIF team_name=BLANKS
    Could any one help me to correct it please.

    Hi,
    Try changeing the line with decode to,
    error_type CHAR(100) "decode(trim(:error_type),NULL, NULL,'Banned',:error_type)" ,
    Cheers

  • Usinging SQL Functions in a Derived Column

    I want to decode values in a column of a sql report. I'm thinking of using a derived item but what is the code (in the HTML Expression field)?. Is this the correct place to do this? The only other way to do this,I believe is in the SQL Definition directly.
    Paul Platt

    Hi Paul,
    I don't quite understand what you are trying to do.
    Is is just a simple decode in a sql report or something more?
    If it's just a simple decode what is it that's not working?

  • Decode in order by clause

    Is it possible to use a decode function in the order by clause, when you have two select statements with a union between? I seem to be getting an error-message telling me to type a number.
    Can anybody help me?

    Tove,
    Is this what you mean?
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(1
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
            10 ACCOUNTING     NEW YORK
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
            40 OPERATIONS     BOSTON
          7369 SMITH          CLERK
          7499 ALLEN          SALESMAN
          7521 WARD           SALESMAN
          7566 JONES          MANAGER
          7654 MARTIN         SALESMAN
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
          7788 SCOTT          ANALYST
          7839 KING           PRESIDENT
          7844 TURNER         SALESMAN
          7876 ADAMS          CLERK
          7900 JAMES          CLERK
          7902 FORD           ANALYST
          7934 MILLER         CLERK
    18 rows selected.Now, to order by the second column, I set the first parameter of the
    DECODE to "2":
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(2
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
            10 ACCOUNTING     NEW YORK
          7876 ADAMS          CLERK
          7499 ALLEN          SALESMAN
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
          7902 FORD           ANALYST
          7900 JAMES          CLERK
          7566 JONES          MANAGER
          7839 KING           PRESIDENT
          7654 MARTIN         SALESMAN
          7934 MILLER         CLERK
            40 OPERATIONS     BOSTON
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
          7788 SCOTT          ANALYST
          7369 SMITH          CLERK
          7844 TURNER         SALESMAN
          7521 WARD           SALESMAN
    18 rows selected.
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(3
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
          7788 SCOTT          ANALYST
          7902 FORD           ANALYST
            40 OPERATIONS     BOSTON
            30 SALES          CHICAGO
          7369 SMITH          CLERK
          7934 MILLER         CLERK
          7900 JAMES          CLERK
          7876 ADAMS          CLERK
            20 RESEARCH       DALLAS
          7566 JONES          MANAGER
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
            10 ACCOUNTING     NEW YORK
          7839 KING           PRESIDENT
          7499 ALLEN          SALESMAN
          7844 TURNER         SALESMAN
          7654 MARTIN         SALESMAN
          7521 WARD           SALESMAN
    18 rows selected.I needed to put the TO_CHAR in the DECODE so all of the columns
    by which I could potentially order are VARCHAR2's, else I was
    getting
    SQL> /
    DECODE(1
    ERROR at line 17:
    ORA-01785: ORDER BY item must be the number of a SELECT-list expressionHTH
    T.

  • Difference between CASE and DECODE

    Hi All,
    Could you please explain me the basic differences between the CASE and DECODE, which performs fast...?
    DECODE is Oracle one, and the CASE is ANSI standard.
    As per my knowledge, CASE is a statement and DECODE is a function which was defined in the Standard package.
    If we use DECODE, the package has to load first, so it will take a little longer than the CASE. CASE is a simple statement which is ANSI standard.
    We can use the CASE in the where clause and can not use the DECODE in the where clause.
    Please clarify me and correct me if anything wrong.
    Thanks,

    IMO, the main important point is the way CASE and DECODE handles NULL
    SQL> select ename,comm,
      2         decode(comm,300,'A',null,'B','C') dcd,
      3         case comm when 300 then 'A'
      4                   when null then 'B'
      5                   else 'C'
      6         end cs
      7  from emp;
    ENAME            COMM D C
    SMITH                 B C --"DECODE treats NULL=NULL. But for CASE, NULL is not equal to "another" NULL
    ALLEN             300 A A
    WARD              500 C C
    JONES                 B C
    MARTIN           1400 C C
    BLAKE                 B C
    CLARK                 B C
    SCOTT                 B C
    KING                  B C
    TURNER              0 C C
    ADAMS                 B C
    JAMES                 B C
    FORD                  B C
    MILLER                B C
    14 rows selected.
    {code}
    Edited by: jeneesh on Jun 3, 2013 1:13 PM
    Note: in CASE, you should use IS NULL
    {code}
    case when comm=300 then 'A'
           when comm is null then 'B'
          else 'C'
    end
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for