A typical decode in where clause

Hi to all,
Could you anybody please give response to my query
select ast.account_num,sup.billing_status_text
from ast,sup
where
(sup.account_status=ast.account_status
or sup.account_status='99999')
Here sup.account_status,ast.account_status are notnull columns..
In the above query duplicates are coming as sup table has 2 rows , one row with matched value for ast.account_status and other row is with sup.account_status= '99999'.
I need to get only one row like
if matched row corresponding to ast.account_status is there in sup , then i need to get ,sup.billing_status_text corresponding to that matched ast.account_status
otherwise i shd get sup.billing_status_text corresponding to sup.account_status='99999' value in sup table
Can we use decode here to remove duplicates....
How to solve this

Hi,
Welcome to the forum!
Whenever you have a question, you should post your sample data in a form that people can use to re-create the problem and thest their soluitons.
For example:
CREATE TABLE     sup
(     ACCOUNT_STATUS          VARCHAR2 (10)
,     BILLING_STATUS          VARCHAR2 (10)
,     SUPPRESSION_FLAG     VARCHAR2 (10)
,     BILLING_STATUS_TEXT      VARCHAR2 (10)
INSERT INTO sup (ACCOUNT_STATUS,     BILLING_STATUS,     SUPPRESSION_FLAG,     BILLING_STATUS_TEXT)
     VALUES     ('99999',          'BB',          '99999',          'Unbill');
INSERT INTO sup (ACCOUNT_STATUS,     BILLING_STATUS,     SUPPRESSION_FLAG,     BILLING_STATUS_TEXT)
     VALUES     ('99999',          'CA',          '99999',          'Unbill');
INSERT INTO sup (ACCOUNT_STATUS,     BILLING_STATUS,     SUPPRESSION_FLAG,     BILLING_STATUS_TEXT)
     VALUES     ('OK',               'CA',          '99999',          'Bill');
INSERT INTO sup (ACCOUNT_STATUS,     BILLING_STATUS,     SUPPRESSION_FLAG,     BILLING_STATUS_TEXT)
     VALUES     ('PE',               'CA',          'N',               'Unbill');
CREATE TABLE     ast
(     account_num     NUMBER
,     ACCOUNT_STATUS     VARCHAR2 (10)
,     BILLING_STATUS     VARCHAR2 (10)
INSERT INTO ast (account_num, account_status, billing_status) VALUES (12356566, 'OK', 'CA');
INSERT INTO ast (account_num, account_status, billing_status) VALUES (96785674, 'AB', 'CA');
COMMIT;It also helps if you post the correct results clearly:
ACCOUNT_NUM BILLING_ST
   12356566 Bill
   96785674 UnbillSo the problem is, when you have more than one output row for the same account_num, you only want to display one of them.
You can do that by ranking the rows, using the analytic ROW_NUMBER function to assign numbers 1, 2, 3, ... to each row, with a different set of numbers for each account_num, and then pciking only the rows that were assigned number 1. (This is called a Top-N Query .)
What makes one row more desireable than another? You said, in the case of account_num=12356566, that it is the row where sup.account_status='OK'. Why? Is that because
(a) 'OK' is always better than 'PE' or '99999', or is it because
(b) 'OK' is also ast.account_status
? I'm guessing that it is (b), but if I'm wrong, you can change the analytic ORDER BY clause below:
WITH     got_rnum     AS
     SELECT      ast.account_num
     ,     sup.billing_status_text
     ,     ROW_NUMBER () OVER ( PARTITION BY  ast.account_num
                         ORDER BY        CASE
                                   WHEN  sup.account_status = ast.account_status
                                   THEN  1
                                   ELSE  2
                                 END
                       ) AS rnum
     FROM      ast
     ,     sup
     WHERE      (     sup.account_status     = ast.account_status
          OR      sup.account_status     = '99999'
     AND     ast.billing_status     = sup.billing_status
SELECT     account_num
,     billing_status_text
FROM     got_rnum
WHERE     rnum     = 1
; The analytic ORDER BY clause is similar to the query ORDER BY clause in that, if there are two or more rows with the same values for the ORDER BY columns, there's no telling in what order those rows will appear. You can add more expressions to the ORDER BY clause as tie-breakers, if necessary.

Similar Messages

  • Can i use Decode in Where clause

    Hi,
    Can i use Decode in Where clause Please Do the need full on the same.
    Thanks,
    Sanjeev.

    set serveroutput on
    DECLARE
    posn  PLS_INTEGER := 0;
    empid PLS_INTEGER := 178;
    x     NUMBER;
    BEGIN
      SELECT NVL(SUM(ah.quantity * ah.saleprice * ap.payoutpct), 0)
      INTO x
      FROM accessoryhistory ah, payoutpercentage ap,
      sku s, store st
      WHERE empid = DECODE(posn,
                              0, st.areadir,
                              1, st.areamgr,
                              2, NVL(st.storemgr1, st.storemgr2),
                              3, NVL(st.asstmgr1, NVL(st.asstmgr2,
                           st.asstmgr3)))
      AND ah.statustype IN ('ACT', 'DEA')
      AND ah.store = st.store
      AND s.dbid = ah.dbid
      AND s.sku = ah.sku
      AND ap.productgroup = s.productgroup
      AND ap.position = posn;
      dbms_output.put_line(x);
    END;
    /http://psoug.org/reference/decode_case.html

  • No output for XML Publisher Report using CASE/DECODE in Where Clause

    Hi,
    I've a business requirement to modify an existing report which has two input parameters,
    -> p_statcode (Closed Status) which can have values 'Y' or 'N'
    -> p_overdue (Overdue Flag) which can have values 'Y' or 'N'
    The Overdue Flag is an evaluated column having values of Y/N and it is evaluated as follows,
    ONTF_MOD_VAL(NVL (
                                         (TRUNC (SYSDATE)
                                          - (TO_DATE (oe_order_lines.attribute18,
                                                      'DD-MON-RRRR')
                                             + TO_NUMBER (fnd_lookup_values.meaning))),
                                         0
                            overdue_flagThe user requirement now is they needs to be a third option for parameter p_overdue called ALL,
    passing which the output should include records having
    p_statcode is Y ELSE p_statcode is N AND p_overdue is Y OR p_overdue is N
    In other words records having both Y and N vlaues for Overdue Flag have to be returned irrespective of the value given to Closed Status.
    Original where clause in the Data Definition file is as follows,
    WHERE Closed_Status = nvl(:p_statcode,Closed_Status)
                       AND overdue_flag = nvl(:p_overdue,overdue_flag)My modified code is as follows,
    WHERE   Closed_Status = NVL (:p_statcode, Closed_Status)
             AND overdue_flag = (CASE
             WHEN :p_overdue = 'Y' THEN 'Y'
             WHEN :p_overdue = 'N' THEN 'N'
             ELSE overdue_flag
             END)
    OR
    WHERE   Closed_Status = NVL (:p_statcode, Closed_Status)
             AND overdue_flag = DECODE (:p_overdue, 'Y', 'Y', 'N', 'N',overdue_flag)Both approaches have the same problem.
    The output is in EXCEL format. The modified query works fine for p_overdue as Y or N but when p_overdue is passed as ALL it returns an empty EXCEL sheet with just the report output column headers.
    Any help as to why this is the case ?? What is wrong in my approach ?
    Regards,
    Vishal

    not clear about p_overdue = ALL
    which values needed for p_overdue = ALL ?
    try smth like
    WHERE   Closed_Status = NVL (:p_statcode, Closed_Status)
    AND (
       overdue_flag = DECODE (:p_overdue, 'Y', 'Y', 'N', 'N',overdue_flag) and :p_overdue != 'ALL'
       or
      :p_overdue = 'ALL' and (overdue_flag = 'Y' or overdue_flag = 'N')
    )for overdue_flag which has more then 'Y', 'N' values
    if overdue_flag only in ('Y','N') then
    WHERE   Closed_Status = NVL (:p_statcode, Closed_Status)
    AND (
       overdue_flag = DECODE (:p_overdue, 'Y', 'Y', 'N', 'N',overdue_flag) and :p_overdue != 'ALL'
       or
      :p_overdue = 'ALL'
    )

  • Using decode in where clause with user defined function

    Hi,
    I have a below query which is failing as the function in the decode taking all cust_account_id as input parameter instead of the one which satisfies the condition in the inner query.So please provide a solution how can i pass only the selected one.
    SELECT hca.cust_account_id
    FROM hz_cust_accounts hca
    WHERE hca.org_id=FND_PROFILE.value('ORG_ID')
    AND hca.cust_account_id = (SELECT DISTINCT hcasa.cust_account_id
    FROM hz_cust_acct_sites_all hcasa
    WHERE hcasa.cust_account_id =hca.cust_account_id
    AND hca.org_id = hcasa.org_id)
    AND DECODE (hca.status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(hca.cust_account_id)) IS NOT NULL
    Thanks,
    Abhilash

    I'm having to guess without access to your tables, but I think changing the IN to a join should produce the same results. The JOIN should be evaluated before applying the WHERE clause, so this may resolve your problem.
    SELECT hca.cust_account_id
    FROM   hz_cust_accounts hca
           INNER JOIN hz_cust_acct_sites_all hcasa
           ON    hcasa.cust_account_id = hca.cust_account_id
           AND   hca.org_id = hcasa.org_id
    WHERE  hca.org_id = FND_PROFILE.value('ORG_ID')
    AND    DECODE (hca.status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(hca.cust_account_id)) IS NOT NULLAlternately, you could next part of the query and break the DECODE into the parent so it is evaluated after the inner query. This is likely uglier from a performance standpoint, though:
    SELECT cust_account_id
    FROM
    SELECT hca.cust_account_id, hca.status
    FROM   hz_cust_accounts hca
    WHERE  hca.org_id=FND_PROFILE.value('ORG_ID')
    AND    hca.cust_account_id = (SELECT DISTINCT hcasa.cust_account_id
                                  FROM   hz_cust_acct_sites_all hcasa
                                  WHERE  hcasa.cust_account_id =hca.cust_account_id
                                  AND    hca.org_id = hcasa.org_id)
    WHERE DECODE (status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(cust_account_id)) IS NOT NULL;

  • Decode in where clause

    Hi all,
    Is there any reason why decode cannot be assigned in the where clause?Shoudl we be using CASE instead ?Appreciate any suggestions.
    SELECT
    decode(abcd,'a','a,'b','b',NULL,'c','c')wxyz,
    from COMB_DATA
    where
    decode(abcd,'a','a,'b','b',NULL,'c','c')wxyz ='a';

    Do not specify aliases for expressions in conditions :-)))

  • Using decode in where clause

    Hi all
    We can use decode function in the Select columns as well as Group by Columns as well as Having Clause
    Can we use decode function in the where clause also. If yes can u give small sample
    Suresh Bansal

    ""DECODE in the WHERE clause"
    http://psoug.org/reference/decode_case.html
      WHERE empid = DECODE(posn,
                              0, st.areadir,
                              1, st.areamgr,
                              2, NVL(st.storemgr1, st.storemgr2),
                              3, NVL(st.asstmgr1, NVL(st.asstmgr2,
                           st.asstmgr3)))

  • Using Decode in where clause in free hand sql

    Hi,
        I want to use decode in free hand sql.
    for eg : this is a where condition
    Outlet_Lookup.City  =  @variable('Enter City')
    Requirement :
    if we put the user prompt as "Enter City and % for all cities"
    and the user enters % then the data display should be all cities or else it shld be the specific city entered in the prmpt..
    Can we do that using Decode statement,
    I have tried
    Outlet_Lookup.City  =  Decode(@variable('Enter City'),'%',Outlet_Lookup.City,(@variable('Enter City')))
    This is not working....
    Pls guide on the same..
    Thanks.

    Hi Mathieu,
            Thanks for the solution,
    I tried the following
    ((Outlet_Lookup.City  =  @variable('Enter City or % for All') or @variable('Enter City or % for All')='%'))
    This is working fine....
    Thanks
    Regards,
    Aparna.

  • Decode in where claus with date comparasion

    hi
    i m using this query can we compare date in decode function in where claue if yes how
    SELECT PPA.START_DATE,
    PPA.END_DATE
    FROM pa_project_assignments PPA,
    PA_CONTROL_ITEMS PCI
    WHERE DECODE(PPA.START_DATE < PCI.ATTRIBUTE1,PCI.ATTRIBUTE1,PPA.START_DATE) BETWEEN (PCI.ATTRIBUTE1) AND (PCI.DATE_REQUIRED)
    AND PPA.END_DATE BETWEEN (PCI.ATTRIBUTE1) AND( PCI.DATE_REQUIRED)
    AND PPA.PROJECT_ID=PCI.PROJECT_ID

    This works.
    SELECT * FROM emp
    WHERE
    CASE WHEN hiredate < SYSDATE THEN
    hiredate
    ELSE SYSDATE
    END BETWEEN SYSDATE-10000 AND SYSDATEIn your CASE
    SELECT PPA.START_DATE,
    PPA.END_DATE
    FROM pa_project_assignments PPA,
    PA_CONTROL_ITEMS PCI
    WHERE
    case when PPA.START_DATE < PCI.ATTRIBUTE1 then
    PCI.ATTRIBUTE1
    else
    PPA.START_DATE
    end  BETWEEN PCI.ATTRIBUTE1 AND PCI.DATE_REQUIRED
    AND PPA.END_DATE BETWEEN  PCI.ATTRIBUTE1 AND PCI.DATE_REQUIRED
    AND PPA.PROJECT_ID=PCI.PROJECT_IDCheers!!!
    Bhushan

  • CASE/DECODE in WHERE caluse

    Hi friends,
    Let's consider an EMP table has the following structure and data:
    create table EMP
    EMPNO NUMBER(4) not null,
    ENAME VARCHAR2(10),
    JOB VARCHAR2(9),
    MGR NUMBER(4),
    HIREDATE DATE,
    SAL NUMBER(7,2),
    COMM NUMBER(7,2),
    DEPTNO NUMBER(2),
    CONFDATE DATE
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7369, 'SMITH', 'CLERK', 7902, to_date('17-12-1980', 'dd-mm-yyyy'), 800, null, 20, to_date('27-12-1980', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7499, 'ALLEN', 'SALESMAN', 7698, to_date('20-02-1981', 'dd-mm-yyyy'), 1600, 300, 30, to_date('28-02-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7521, 'WARD', 'SALESMAN', 7698, to_date('22-02-1981', 'dd-mm-yyyy'), 1250, 500, 30, to_date('28-02-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7566, 'JONES', 'MANAGER', 7839, to_date('02-04-1981', 'dd-mm-yyyy'), 2975, null, 20, to_date('12-04-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7654, 'MARTIN', 'SALESMAN', 7698, null, 1250, 1400, 30, to_date('28-09-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7698, 'BLAKE', 'MANAGER', 7839, to_date('01-05-1981', 'dd-mm-yyyy'), 2850, null, 30, to_date('11-05-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7782, 'CLARK', 'MANAGER', 7839, to_date('09-06-1981', 'dd-mm-yyyy'), 2450, null, 10, to_date('19-06-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7788, 'SCOTT', 'ANALYST', 7566, null, 3000, null, 20, to_date('09-12-1982', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7839, 'KING', 'PRESIDENT', null, to_date('17-11-1981', 'dd-mm-yyyy'), 5000, null, 10, to_date('27-11-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7844, 'TURNER', 'SALESMAN', 7698, to_date('08-09-1981', 'dd-mm-yyyy'), 1500, 0, 30, to_date('18-09-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7876, 'ADAMS', 'CLERK', 7788, null, 1100, null, 20, to_date('12-01-1983', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7900, 'JAMES', 'CLERK', 7698, null, 950, null, 30, to_date('03-12-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7902, 'FORD', 'ANALYST', 7566, to_date('03-12-1981', 'dd-mm-yyyy'), 3000, null, 20, to_date('13-12-1981', 'dd-mm-yyyy'));
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
    values (7934, 'MILLER', 'CLERK', 7782, to_date('23-03-1981', 'dd-mm-yyyy'), 1300, null, 10, to_date('31-05-1981', 'dd-mm-yyyy'));
    commit;
    Now I need to fetch the employees whose hire date is between 01-APR-1981 and 31-DEC-1981. If the hire date is null, then confirmation date has to be considered.
    For this input the following employees's records should be returned:
    7566
    7654
    7698
    7782
    7839
    7844
    7900
    7902
    I tried with CASE, DECODE in WHERE clause. But I couldn't succeed. Please help.
    Thanks in advance.
    Iniyavan

    SQL> ed
    Wrote file afiedt.buf
      1* select * from emp_test where nvl(hiredate,confdate)  between '01-APR-1981' and '31-DEC-1981'
    SQL> /
    EMP_TESTNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO CONFDATE
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20 12-APR-81
          7654 MARTIN     SALESMAN        7698                 1250       1400         30 28-SEP-81
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30 11-MAY-81
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10 19-JUN-81
          7839 KING       PRESIDENT            17-NOV-81       5000                    10 27-NOV-81
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30 18-SEP-81
          7900 JAMES      CLERK           7698                  950                    30 03-DEC-81
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20 13-DEC-81
    8 rows selected.@boopathi: Why to_char is needed here ? Further to_char(hire date,'DD_MON_YY') and comparing with '01-APR-1981' ? and WHAT is "_" doing in date format ? You sholud test your query before posting.
    Edited by: Saubhik on May 17, 2010 11:33 PM

  • Using decode to define "where" clause

    Gurus,
    Before, I was unioning several queries to get my desired results. Is there a way to utilize decode to define my "where" conditions?
    Thanks
    msi.global_attribute1               HTS_Number,           
    msi.global_attribute2               ECCN_Number  ,
    msi.market_price                    price,     --- double-check
    decode(msi.serial_number_control_code,5,'Serial','Lot') control_type,
    -- add item_type
    --Item Label Creation        At Receipt or At Sales Order Issue
    (case
    when enabled_flag = 'Y' and end_date_active is null then 'Active'
    when enabled_flag = 'Y' and end_date_active > sysdate then 'Active'
    when enabled_flag = 'Y' and end_date_active < sysdate then 'Inactive'
    when enabled_flag = 'N' then 'Inactive'
    else 'Active'
    end) status,
    from inv.mtl_system_items_b   msi,
         po_hazard_classes    phc,
        po_un_numbers        pun
    where msi.hazard_class_id = phc.hazard_class_id(+)  
    and   msi.un_number_id = pun.un_number_id(+)   
    and   msi.organization_id = 543
    and   msi.creation_date = msi.last_update_date
    --and   'New Items' = nvl(p_item_status,'All Items') --p_item_status
    and   decode('New Items', --p_item_status,
          'New Items', (msi.creation_date = msi.last_update_date),
          'Updated Items', (msi.creation_date <> msi.last_update_date),
          'All Items', (1=1), (1=1))
      and msi.segment2 = '14078'

    Hi,
    sreese wrote:
    Before, I was unioning several queries to get my desired results. Is there a way to utilize decode to define my "where" conditions?Depending on what you mean, yes.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Simplify the problem as much as possible. Remove all tables and columns that play no role in this problem.
    Always say which version of Oracle you're using.
    Here's an example of two UNIONed queries:
    SELECT       deptno
    ,       SUM (sal)     AS total_sal
    ,       'MANAGEMENT'     AS grp_name
    FROM       scott.emp
    WHERE       job     IN ('MANAGER', 'PRESIDENT')
    GROUP BY  deptno
         UNION ALL
    SELECT       deptno
    ,       SUM (sal)     AS total_sal
    ,       'OLD-TIMERS'     AS grp_name
    FROM       scott.emp
    WHERE       hiredate     < DATE '1984-01-01'
    GROUP BY  deptno
    ORDER BY  deptno
    ,            grp_name
    ;Output:
    `   DEPTNO  TOTAL_SAL GRP_NAME
            10       7450 MANAGEMENT
            10       8750 OLD-TIMERS
            20       2975 MANAGEMENT
            20       6775 OLD-TIMERS
            30       2850 MANAGEMENT
            30       9400 OLD-TIMERSA more efficient way to get the same information, without a UNION is:
    SELECT       deptno
    ,       SUM (CASE WHEN job IN ('MANAGER', 'PRESIDENT') THEN sal END)     AS management
    ,       SUM (CASE WHEN hiredate < DATE '1984-01-01'      THEN sal END)     AS old_timers
    FROM       scott.emp
    WHERE       job          IN ('MANAGER', 'PRESIDENT')
    OR       hiredate     < DATE '1984-01-01'
    GROUP BY  deptno
    ORDER BY  deptno
    ;Output:
    `   DEPTNO MANAGEMENT OLD_TIMERS
            10       7450       8750
            20       2975       6775
            30       2850       9400As you can see, the results aren't exactly the same. UNION makes it easy to get more rows in the output than there are in the original; CASE (or DECODE,you can use whichever you like) makes it easy to get fewer rows and more columns. If you reallt want one kind of output or the other, it can be done with a little more work using either UNION or CASE.
    When using CASE, the WHERE clause is typically more inclusive than any of the WHERE caluses in the UNION. Some of the conditions (in this example, all of the conditions) that were in the separate WHERE clauses of the UNION get changed to be conditions in separate CASE expressions.

  • Problem with DECODE block in WHERE clause

    Hi,
    I'm facing problem with DECODE statement. I just simulated my problem in the simple way as follows. If I execute this following query, I should get "hello", but I'm not getting anything (ZERO rows returned).
    SELECT 'hello' FROM DUAL
    WHERE 'sample1' in (DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',
    2, '''sample4'', ''sample5'', ''sample6'''
    I think some problem is there in my WHERE clause.
    But When I'm exeucting the following query as a seperate query, then I'm getting the value of DECODE block properly, but didn;t understnad why its not returning the same way when I'm putting the same DECODE statement in WHERE clause.
    SELECT DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',
    2, '''sample4'', ''sample5'', ''sample6'''
    FROM DUAL;
    Please help me to get out of this problem. Thank you so much in advance.
    Thanks,
    Ramji.

    The value returned by SELECT DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',2, '''sample4'', ''sample5'', ''sample6''') FROM DUAL;
    'sample1', 'sample2', 'sample3' is a single string. Consider it x.
    SELECT 'hello' FROM DUAL WHERE 'sample1' in ( DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',2, '''sample4'', ''sample5'', ''sample6'''));
    is like SELECT 'hello' FROM DUAL WHERE 'sample1' in ('x');
    or
    SELECT 'hello' FROM DUAL WHERE 'sample1' in ('''sample1'', ''sample2'', ''sample3''') and not
    SELECT 'hello' FROM DUAL WHERE 'sample1' in ('sample1', 'sample2', 'sample3');
    For this same reason SELECT 'hello' FROM DUAL WHERE 'sample1' in (select '''sample1'', ''sample2'', ''sample3''' from dual);
    also does'nt work.
    Please use INSTR to find whether 'sample1' exists in the string 'sample1', 'sample2', 'sample3'.

  • Decode/Case in Where clause

    Hello,
    We are experiencing an issue with a Select statement that uses Decode in the Where clause. Specifically, it seems to be ignoring a nested Decode and just returning the default value. We have another nested decode that works fine, though.
    A member of our team mentioned that he believed there was an issue with using Decode and Case statements inside of a where clause within HTML DB...Is this correct? If it is, is there a workaround? Since the nested Decode works elsewhere in this statement, that doesn't seem right.
    My select statement looks like:
    SELECT
       SUBSTR(OBOB.OBOB_CNAME, 0, 30) d,
       OBOB.OBOB_UID r
    FROM
       ISR_OBOB_OBJECT OBOB,
       ISR_OBAF_OBJECT_AFFILIATION OBAF,
       ISR.ISR_OBSD_SDR OBSD
    WHERE
       OBOB.OBOB_UID = OBSD.OBOB_UID AND
       OBOB.OBOB_UID = OBAF.OBOB_B_UID AND
    /*If Personal radio button is selected, displays all SDRs associated with user.
      If All is selected, displays all SDRs associated with IS group selected from drop down list
          or every SDR.
       OBAF.OBOB_A_UID = DECODE(:P1_DISPLAY_ALL,
                                       'Personal', :F101_APP_USER_UID,
    /*This is the decode statement that it seems to ignore. If ALL is selected, the query should see if a group has
        has been selected from a drop down list that appears when the ALL button is chosen. If a group is selected
        (the item isn't 0), only SDRs for that group should be shown. Otherwise, all SDRs for every group should display.
                                       'ALL', DECODE(:P1_SEARCH_IS_SUPPORT_GROUP, 0, OBAF.OBOB_A_UID, :P1_SEARCH_IS_SUPPORT_GROUP),
                                       OBAF.OBOB_A_UID) AND
    /*If Personal radio button is selected, display SDRs where user is the Primary assignee.
       OBAF.OBAT_UID = DECODE(:P1_DISPLAY_ALL, 'Personal', (select OBAT_UID from ISR_OBAT_OBJ_AFFIL_TYPE WHERE OBAT_APP_REF = 'SDR_PRIMARY'), OBAF.OBAT_UID) AND
    /*If a SDR Status (open, completed, on hold, not started...) is selected, only display the SDRs with that status.
       OBSD.KTTR_STATUS_UID = DECODE(:P1_ISR_STATUS_UID, 0, OBSD.KTTR_STATUS_UID, :P1_ISR_STATUS_UID) AND
    /*If SDR_History textbox is Null, or Open, Not Started, or On Hold SDR status has been selected, then all SDRs with
        a create date between today and 99999 months ago will display. Otherwise, only SDRs with a create date between
        today and however many months are in the textbox will display (i.e. Completed SDRs created in the past 6 months.)
       MONTHS_BETWEEN(sysdate, OBSD.OBSD_CREATE_DATE) <= DECODE(:P1_SDR_HISTORY, NULL, 99999, DECODE(:P1_ISR_STATUS_UID,
                                                              (select KTTR_UID from ISR_KTTR_TRANSLATION where KTTR_APP_REF = 'SD_STAT_OPEN'), 99999,
                                                              (select KTTR_UID from ISR_KTTR_TRANSLATION where KTTR_APP_REF = 'SD_STAT_NOT_STA'), 99999,
                                                              (select KTTR_UID from ISR_KTTR_TRANSLATION where KTTR_APP_REF = 'SD_STAT_HOLD'), 99999,
                                                              :P1_SDR_HISTORY))
    /*Alphabetical order
    Order by
       dWe originally wrote this as a PL/SQL statement that returned a query string since most of the where clause is dependent on items the user may or may not select, but we have moved the query into a multiselect list, which only seems to allow SQL Queries.
    Any help or advice would be appreciated.
    Thanks,
    Scott

    Scott: Did you try running that SQL statement in SQL Workshop in Apex? You can run it as it is, it will popup a window asking you to enter values for the bind variables.
    JAC73: I don't think an IN clause doesn't work that way, you need a actual SQL sub-query, not an expression from a DECODE/CASE statement. Search this site for str2tbl and see Tom's excellent discussion at
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:110612348061

  • Use of DECODE and NULL value in a WHERE clause

    hi all,
    I came into an issue trying to use the DECODE function in a simple where clause.
    this is my test case
    CREATE TABLE tab_test (lev NUMBER, code VARCHAR2(10), val VARCHAR2(10));
    INSERT INTO tab_test VALUES (1, NULL, 'val11');
    INSERT INTO tab_test VALUES (1, NULL, 'val12');
    INSERT INTO tab_test VALUES (1, '13', 'val13');
    INSERT INTO tab_test VALUES (2, '21', 'val21');
    INSERT INTO tab_test VALUES (1, '22', 'val22');
    INSERT INTO tab_test VALUES (1, '23', 'val23');
    and this is the query
    SELECT * FROM tab_test WHERE code = DECODE(:lev,1,NULL,:cod)
    as you can see running this query, setting :lev to 1 will return an empty record set, instead of the expected first two rows (as it will be, running "select * from tab_test where code is null").
    is there a way to overcome this issue? thanks for help

    hi Frank,
    I can confirm that the queries do work when run on TOAD, but do not when they are put in the WHERE clause of my data block. I guess the problem relies on some data block setting; I should investigate on Forms forum.
    Anyway, here is my test case, including data and some examples. You can realize that it works good
    CREATE TABLE TAB_TEST
    LEV NUMBER,
    CODE VARCHAR2(10 BYTE),
    VAL VARCHAR2(10 BYTE)
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (3, 'val21', 'val3_211');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val21', 'val3_212');
    Insert into tab_test
    (LEV, VAL)
    Values
    (1, 'val11');
    Insert into tab_test
    (LEV, VAL)
    Values
    (1, 'val12');
    Insert into tab_test
    (LEV, VAL)
    Values
    (1, 'val13');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val11', 'val21');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val12', 'val22');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val13', 'val23');
    COMMIT;
    SELECT * FROM TAB_TEST
    CONNECT
    BY PRIOR val = code
    START WITH (CASE
    WHEN :LIV = 1 AND code IS NULL THEN 'OK'
    WHEN :LIV != 1 AND code = :COD THEN 'OK'
    END = 'OK')
                   AND VAL = :V
    :LIV = 1
    :COD = [any]
    :V = 'val11'
    LEV     CODE     VAL
    1          val11
    2     val11     val21
    3     val21     val3_211
    3     val21     val3_212
    :LIV = 1
    :COD = [any]
    :V = 'val12'
    LEV     CODE     VAL
    1          val12
    2     val12     val22
    :LIV = 2
    :COD = 'val11'
    :V = 'val21'
    LEV     CODE     VAL
    2     val11     val21
    3     val21     val3_211
    2     val21     val3_212

  • DECODE is not working in WHERE clause when subquery returns more rows

    Hi Gurus,
    I want to write a query on CCENTERS table(Script given below) and expect the following result:
    1. When I pass a value of 0 for ID, It returns all the rows given in the table.
    2. When I pass a value other than 0, It returns the row for the given value as well as all its child records.
    CCENTER has parent-child relationship in ID and BASE column. I am using a query with DECODE function. but DECODE function in WHERE clause is not capable of handling sub-query with multiple rows.
    VARIABLE ParaCCenter NUMBER
    BEGIN
    :paraccenter:=0;
    END;
    CREATE TABLE ccenters
    (id NUMBER,
    name VARCHAR2(20),
    base number);
    INSERT INTO ccenters VALUES(1,'NUST',null);
    INSERT INTO ccenters VALUES(2,'SEECS',1);
    INSERT INTO ccenters VALUES(3,'NBS',1);
    commit;
    SELECT * FROM ccenters
    WHERE id IN DECODE(:ParaCCenter, 0, id,
    (SELECT id FROM ccenters
    START WITH base=:ParaCCenter
    CONNECT BY PRIOR id = base
    UNION
    SELECT :ParaCCenter FROM dual
    BEGIN
    :paraCCenter:=1;
    END;
    SELECT * FROM ccenters
    WHERE id IN DECODE(:ParaCCenter, 0, id,
    (SELECT id FROM ccenters
    START WITH base=:ParaCCenter
    CONNECT BY PRIOR id = base
    UNION
    SELECT :ParaCCenter FROM dual))
    The result is
    (SELECT id FROM ccenters
    ERROR at line 3:
    ORA-01427: single-row subquery returns more than one row
    How this query can be rewritten for the given functionality. Any response will be highly appreciated.
    Thanks

    And if you want to use DECODE:
    SQL> BEGIN
      2  :paraccenter:=0;
      3  END;
      4  /
    PL/SQL procedure successfully completed.
    SQL> select  *
      2    from  ccenters
      3    where :paraccenter = decode(:paraccenter,0,0,id)
      4  /
            ID NAME                       BASE
             1 NUST
             2 SEECS                         1
             3 NBS                           1
    SQL> BEGIN
      2  :paraccenter:=2;
      3  END;
      4  /
    PL/SQL procedure successfully completed.
    SQL> select  *
      2    from  ccenters
      3    where :paraccenter = decode(:paraccenter,0,0,id)
      4  /
            ID NAME                       BASE
             2 SEECS                         1
    SQL> SY.

  • How can we use DECODE function in where clause.

    Hi Guys,
    I have to use DECODE function in where clause.
    like below
    select * from tab1,tab2
    where a.tab1 = b.tab2
    and decode(code, 'a','approved')
    in this manner its not accepting?
    Can any one help me on this or any other aproach?
    Thanks
    -LKR

    >
    I am looking for to decode the actual db value something in different for my report.
    like if A then Accepted
    elseif R then Rejected
    elseif D then Denied
    these conditions I have to check in where clause.
    >
    what are you trying to do?
    may be you are looking for
    select * from tab1,tab2
    where a.tab1 = b.tab2
    and
       (decode(:code, 'A','Accepted') = <table_column>
        or
        decode(:code, 'R','Rejected') = <table_column>
       or
        decode(:code, 'D','Denied') = <table_column>
       )

Maybe you are looking for

  • Java stack and ABAP stack in upgrading SP

    Hi, pls pardon if it appears silly question. I dont have much knowledge in Basis I am on XI3.0 with SP 09 and upgrading SP to SP20 from SAP service market place. How can I identify which is java stack and which is ABAP stack in evrery SP because Java

  • How to Reuse Business Rules

    Hi, I've created a composite business rule and exposed as a composite, if i want to call reuse that business rule in multiple bpel processes, how can i do it? Any help would be appreciated, thank you :) Thx, Rahul venkat

  • Top of video being cut off

    Hello, When I add a video to the timeline, it crops the top of the picture out.I don't have safe margins selected, so I don't know why it's doing this, It's a bigger issue on some shots because it cutting off the top of someone's head. Is there a way

  • Where is decimal in numbers

    How can I change the decimal in numbers Aftre the upgrade I miss these icons

  • 10g database, cluster on aix and jdeveloper

    Are there some known incompatibilities between oracle 10g database with cluster on aix and jdeveloper application (jdev 10g) using dynamic jdbc credentials (jsp, bc4j, adf)?