Logical operations in SQL decode function?

Hello
Is it possible to perform logical operations in SQL decode function

as
' > '
' < '
' > ='
' < ='
'<>'.
not in
in
non-null
a null value

for example...

Select col1, order_by, decode (col1, > 10, 0, 1)
tab;

Select col1, order_by, decode (col1, <>0, 10, 1)
tab;

Select col1, order_by, decode (col1, not in (10,11,12), 0, 1)
tab;

Select col1, order_by, decode (col1, is set to null, 0, 1).
tab;




Kind regards

infantry

Published by: user780731 on April 30, 2009 12:07 AM

Published by: user780731 on April 30, 2009 12:07 AM

Published by: user780731 on April 30, 2009 12:08 AM

Published by: user780731 on April 30, 2009 12:08 AM

Published by: user780731 on April 30, 2009 12:09 AM

example:

select col1 ,order_by,case when col1 > 10 then 0 else 1 end
from tab;

select col1 ,order_by,case when col1 <> 10 then 0 else 1 end
from tab;

select col1 ,order_by,case when col1 not in (10,11,12) then 0 else 1 end
from tab;

Regarding testing for null, decode the handles which, by default, anyway, so that you can get decode or case easily...

select col1 ,order_by,decode (col1, null , 0 , 1)
from tab;

select col1 ,order_by,case when col1 is null then 0 else 1 end
from tab;

Tags: Database

Similar Questions

  • SQL DECODE function

    Hi all

    I have the scenario where I have to post as below.

    VIEW: MILSTN_ACTUAL_DATE if the data shows ELSE use MILSTN_PSSTRGT_DTE
     SELECT
      T4.MILSTN_ACTUAL_DATE       LastMilestoneDate,
         FROM  DW_PROJECT        T1,
                  DW_PROJ_H   T2,
            

    Hello

    This looks like a job for COALESCE:

    COALESCE ( TO_CHAR (milstn_actual_date, 'DD-Mon-YYYY')
          , TO_CHAR (milstn_psstrgt_dte, 'DD-Mon-YYYY')
          , 'NO MILESTONE REDCORDED
          )
    

    COALESCE returns the first argument not NULL.
    All arguments must have the same data type. Among the possibilities being a string ("No. MILESTONE REGISTERED'), which means the other arguments cannot be DATEs. you need to convert DATEs to strings.

    You can't find it confusing to use the DATE in a column, but DTE name in another? How do you remember whether or not you want to use an 'A'? You'll save yourself (and one who must maintain the code after you have) a lot of trouble if you deciide on a spelling and use cionsitently.

    I hope that answers your question.
    If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and also publish outcomes from these data.
    Explain, using specific examples, how you get these results from these data.
    Always tell what version of Oracle you are using.

  • How to switch OR logic in DECODE function?

    There is somewhere in my PL/SQL code as embedded in other SQL code. SELECT SUM (DECODE(COL1,'AB',COL2,'AC',COL2,'AD',COL2,'AF',COL2)) FROM DUAL you can see if COL1 is AB, AC, AD, or AF it returns COL2. I was worrying if it takes more execution time. Is there a better way to do this. We can pass the OR logical operator in DECODING so that all objects to check can be passed at any given time? I'm on Oracle 10 g.

    I'd not concerned that such internal function has a performance impact unless you have encountered a specific situation and have evidence to support.

    As others have shown, the other option to DECODE (which is specific Oracle) is to use the CASE (which is ANSI standard), and the CASE is also more flexible in terms of test conditions.

    Performance wise, however, there is little difference between the two.

  • SQL Loader: Help TRIM and Decode functions please

    Hello

    I have load data from a flat file, for some columns, I need to use the TRIM and DECODE functions. It's a pipe delimited file.

    I get a syntax error (one is lower) same error listed for GARNISH.

    SQL * Loader-350: at line xx syntax error.
    Expected ', 'or') ', found 'DECODE '.


    ===========
    , FINAL_BILL_DATE CHAR (30) "TRIM(:FINAL_BILL_DATE)".
    , BUSINESS_ID 'DECODE(:BUSINESS_ID,'B',1,'C',2,'E',3,'G',4,'O',5,'R',6,'T',7,'U',8,'H',9,-1) '.


    Can someone please help.

    Thank you
    Josiane

    Hello josiane.
    The error you receive leads me to believe that at some point before the DECODING on the BUSINESS_ID line, probably some line before the FINAL_BILL_DATE line, it is a syntactic error causing the quotes before DECODING actually put an end to some other syntaxes. Without any lines that might actually contribute to this, including details of the header, it's the best I can advise.

    Hope this helps,
    Luke

    Please check the answer as helpful or response, if it is so. If this is not the case, further clarification.
    Try to always provide create table and table insert to help members of the forum to help you.

  • Decode function in the Update statement

    Hi all

    I'm writing a query where I can update a pastdue_fees column in a table of book_trans based on a difference between the return_dte and due_dte columns.

    I use Oracle SQL. That's what I have so far for my decoding function:

    SQL > SELECT
    2 DECODE (SIGN ((return_dte-due_dte) * 2),)
    3 '-1 ', ' 0',
    4 '1', '12', 'Null')
    5 FROM book_trans;

    DECO
    ----
    Null value
    12
    Null value
    0

    If the logic is that, if the sign is - 1, the value in the return_dte column must be 0; If it is + 1, then it has 12 and everything else is Null.

    So now, I have to conclude my function of decoding of the update statement to update the columns. However, I get the error messages.

    The logic should be:
    UPDATE book_trans SET PastDue_fees = decode (expression)

    I gave him a few different tests with the following results:

    SQL > UPDATE book_trans
    2 SET pastdue_fees = SELECT
    3 DECODE (SIGN ((return_dte-due_dte) * 2),)
    4 '-1 ', ' 0',
    5 '1', '12', 'Null')
    6 FROM book_trans.
    SET pastdue_fees = SELECT
    *
    ERROR on line 2:
    ORA-00936: lack of expression


    SQL > UPDATE book_trans
    2 SET pastdue_fees =
    3 DECODE (SIGN ((return_dte-due_dte) * 2),)
    4 '-1 ', ' 0',
    5 '1', '12', 'Null')
    6 FROM book_trans.
    OF book_trans
    *
    ERROR on line 6:
    ORA-00933: SQL not correctly completed command.

    Any help or advice would be greatly appreciated I got SQL for about six weeks and not very competent!

    Thank you!

    882300 wrote:
    Hi all

    I'm writing a query where I can update a pastdue_fees column in a table of book_trans based on a difference between the return_dte and due_dte columns.

    I use Oracle SQL. That's what I have so far for my decoding function:

    SQL > SELECT
    2 DECODE (SIGN ((return_dte-due_dte) * 2),)
    3 '-1 ', ' 0',
    4 '1', '12', 'Null')
    5 FROM book_trans;

    DECO
    ----
    Null value
    12
    Null value
    0

    If the logic is that, if the sign is - 1, the value in the return_dte column must be 0; If it is + 1, then it has 12 and everything else is Null.

    So now, I have to conclude my function of decoding of the update statement to update the columns. However, I get the error messages.

    The logic should be:
    UPDATE book_trans SET PastDue_fees = decode (expression)

    I gave him a few different tests with the following results:

    SQL > UPDATE book_trans
    2 SET pastdue_fees = SELECT
    3 DECODE (SIGN ((return_dte-due_dte) * 2),)
    4 '-1 ', ' 0',
    5 '1', '12', 'Null')
    6 FROM book_trans.
    SET pastdue_fees = SELECT
    *
    ERROR on line 2:
    ORA-00936: lack of expression

    SQL > UPDATE book_trans
    2 SET pastdue_fees =
    3 DECODE (SIGN ((return_dte-due_dte) * 2),)
    4 '-1 ', ' 0',
    5 '1', '12', 'Null')
    6 FROM book_trans.
    OF book_trans
    *
    ERROR on line 6:
    ORA-00933: SQL not correctly completed command.

    Any help or advice would be greatly appreciated I got SQL for about six weeks and not very competent!

    Thank you!

    If you really really really want to update the entire table, the syntax would be...

    UPDATE book_trans
       SET
          pastdue_fees  = DECODE(SIGN((return_dte - due_dte)*2), -1, 0, 1, 12, Null);
    

    I took out all the single quotes. If you actually have a string column and store all numbers in there so it must be reported as a NUMBER column and not a column of type character (varchar2).

    ALWAYS use the appropriate data type, it will save you a ton of headaches in the future.

    Also, since you are new to the forum, please read the FAQ to learn etiquette and what not.

    http://wikis.Sun.com/display/Forums/Forums+FAQ

  • Logical operations on a string of bits

    Hi, I have a very simple question that I can't seem to understand.  I'd just like to perform logical operations (AND, GOLD, etc.) on 2 strings of bits that are 24 bits long each, however I can't find in the palette of functions a function that acts as a binary constant.  I see that constant digital and hex functions.  You can somone please let me know where I can find it.  For example, I would AND ' 111111111111111111111111 '& ' 000000000000000000000000'.

    You know the difference between numeric and string data types in LabVIEW? Blue = digital = integer. Pink = string. In the example you linked to, they use an integer constant when the display format is set to "binary". The 'b' of the constant indicates the radix, which in this case is 'binary '. Right-click on a digital constant and you can change its display format. You can select one of the predefined formats or you can specify a by clicking on the option "Advanced Editing Mode. Eligible formats are defined by using LabVIEW. For example

    %b = binary

    % 8 b = binary, using the width of minimum field of 8, fills spaces (for example, '1101')

    % 08 = binary, using 8 minimum field width, filled with zeros (for example, "00001101")

  • using utl_encode.base64_encode to the breast to decode function

    Hi, I want to use utl_encode.base64_encode to decode function. However, the result is not as expected.

    Select 'a', decode ('a', ' 1 ',' EQUAL to 1',)
    "Is NOT EQUAL to 1'.
    utl_encode.base64_encode ('a')
    ) result
    of the double


    A RESULT
    a 43673D3D

    43673D3D is not a value encoded as a base64

    What is the problem with sql?

    Thank you
    SQL> select 'a'
      2  ,      utl_encode.base64_encode(utl_raw.cast_to_raw('a')) raw_result
      3  ,      utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw('a'))) string_result
      4  from   dual;
    
    ' RAW_RESULT      STRING_RESULT
    - --------------- ---------------
    a 59513D3D        YQ==
    
    1 row selected.
    

    Keep in mind that utl_encode.base64_encode returns a RAW and needs FIRST entries.
    You will probably need UTL_RAW to get the desired results.
    http://download.Oracle.com/docs/CD/B19306_01/AppDev.102/b14258/u_encode.htm#CACECFHF

  • With regard to the decode function

    Hi all

    I want to know abt decode function in sql-oracle
    I... e passing parameters to decode using decode using the ': ' bind the parameter

    Select the WORK, decode(:j,'CLERK','MANAGER','ANALYST','EXEC',JOB) of EMP;
    I declared the variable j in sql environment
    VARCHAR2 (20) OF THE VARIABLE J;
    I have the query exec
    and had the clerk as an input parameter
    but the o/p as iam
    JOB DECODE(:J)
    --------- ---------
    MANAGER
    MANAGER
    MANAGER
    SELLER SELLER
    SELLER SELLER
    SELLER SELLER
    CLERK CLERK
    SELLER SELLER
    THE ANALYST ANALYST
    CLERK CLERK
    THE ANALYST ANALYST

    JOB DECODE(:J)
    --------- ---------
    CLERK CLERK

    12 selected lines.

    SQL > PRINT J;

    J
    --------------------------------------------------------------------------------

    im not getting o/p
    so please hlelp me only: should be used not &
    This is my first thread.
    execuse me if no errors

    tons of thanks in advance to all

    Hello

    We can try like this...

    Begin
    : j: = 'CLERK ';
    end;
    /

    then, we execute your SQL query as below...

    Select the WORK, decode(:j,'CLERK','MANAGER','ANALYST','EXEC',JOB) OF the EMP
    where JOB =: j;

    I think that this will solve your problem

    Kind regards
    Soak the Sevin rana

  • OBIEE 10 g: Promoted filter does not use BETWEEN operator in SQL

    I have a prompt with operator control and Calendar is between . During the initial loading a sql report uses the BETWEEN operator in SQL very well (because is invited filter). But when a new date is selected and click on GO, it shows < = operator in the SQL instead.

    Expected:

    AND T9610. "" calendar_date "between CONVERT(DATETIME, '2015-01-15 00:00:00', 120) AND...

    Actual result:

    AND T9610. "" calendar_date "< = CONVERT (DATETIME, ' 2015-01-15 00:00:00 ', 120)

    We are moving from Windows server 2003 to 2008. Our development app. works very well, it always uses the BETWEEN operator. but our new production and uat approx. has this problem. I confirmed the sub elements between environments.

    RPD

    Catalog

    Version 10.1.3.4.2 (Build 110727.2045)

    InstanceConfig.Xml

    DBFeatures.ini

    NQSConfig.ini

    SQL Server 2008 R2

    Windows Server 2008

    My research of existing patches show everything to be due to my problem. What else could be missing?

    Turns out that I have wrong set of resource files (res folder), they'RE pointing to. Once I directed to the other game that worked.

  • How to configure the settings of sql stored function

    Hello

    I use jdeveloper 11.1.2.3.0

    I have the below sql stored function
    function get_data(p_id     in number,
                      p_date   in date,
                      p_msg    out varchar) return number is
     .......
    
    end get_data;
    I would like to know how exactlly I should call this function of my AppModuleImpl.
    I tried several ways to set the parameters, but I'm getting java.sql.SQLException: Error invalid column index.

    Could you give me the correct code for this case?

    Thank you very much!

    check the docs [url http://docs.oracle.com/cd/E16162_01/web.1112/e16182/bcadvgen.htm#insertedID6] calling stored procedures and functions

  • Evaluation of the regular expression with logical operator

    Hi all

    I am little confused with expression with logical operator evaluation. I'm trying to understand the in expression.

    -----
    eXa.getTrue () & & eXa.getFalse () | eXa.getFalse () & & eXa.getTrue () | eXa.getFalse () is false and True Count: 1 False Count: 3

    According to the agreement, it should be true with True Count: 1 False Count: 3
    It must run the 1 getTrue() then 1stGetFalse() and getfalse() then 2nd jump 2nd getTrue() and must run 3rd fetFalse()

    -----
    eXa.getTrue () & & eXa.getTrue () | eXa.getFalse () & & eXa.getTrue () | eXa.getFalse () is true and true count: 2 False Count: 0

    According to the agreement, it should be true with True Count: 3 False Count: 0
    He must run getTrue() 2 1 1 getFalse() jump and run 3rd getTrue() and jump the last getFalse().

    -----
    eXa.getTrue () | eXa.getFalse () & & eXa.getFalse () | eXa.getTrue () & & eXa.getFalse () presents itself as true and true count: 1 False Count: 0

    According to the agreement, it should be true with True Count: 2 False Count: 2
    It must run 1 getTrue() and jump getFalse() 1st run 2nd getFalse() and then run getTrue() 2nd and 3rd then getFalse()

    Please, help me understand above expressions.


    Here is the definition of methods:

    Private boolean getTrue() {}
    trueCount ++;
    Boolean retrunValue = 4 > 3;
    Return retrunValue;
    }

    Private boolean getFalse() {}
    falseCount ++;
    Boolean retrunValue = 3 > 4;
    Return retrunValue;
    }


    Thanks for your help

    >

    added parentheses to make order of the most obvious BSP. adding a "?" to show calls not executed.

    (eXa.getTrue() && eXa.getFalse()) || (eXa.getFalse() && eXa.getTrue()) || eXa.getFalse()  comes as false and True Count: 1 False Count: 3
    
    (T && F) = F
    (F && ?) = F
    (F) = F
    
    F || F || F = F
    
    (eXa.getTrue() && eXa.getTrue()) || (eXa.getFalse() && eXa.getTrue()) || eXa.getFalse()  comes as true and True Count: 2 False Count: 0 
    
    (T && T) = T
    (? && ?) = ?
    (?) = ?
    
    T || ? || ? = T
    
    eXa.getTrue() || (eXa.getFalse() && eXa.getFalse()) || (eXa.getTrue() && eXa.getFalse())  comes as true and True Count: 1 False Count: 0
    
    (T) = T
    (? && ?) = ?
    (? && ?) = ?
    
    T || ? || ? = T
    
  • Query SQL or function...

    Hi everyone,
    
    
      Please help me to clarify this question
    I have a "patient" table and a "address" table.And each patient has differnt types of addresses
    like PMI,Mailing and default address i need to pick patient address in the order of preference
    (PMI,Mailing ,Default)
    
    I have two options to get the address of a patient.Either write a SQL query to get the address of a 
    patient(according to preference)
    or write a function which checks
    
     if there is PMI,Mailing and default
      take PMI
     or
     If there is mailing and Default
     take mailing
     or
     take default.
    
    which one is the best method to get the address of a patient?  SQL query or function..
    Definitely everyone will say that it should be direct SQL query instead of multiple function calls.
    
    But in my organization there are many developers which will get "patient address" in their application 
    or SQL code or PL/SQL code or from some
    'X' Business intelligence tool.
    At this scenario is it best to have a function which every one will call and get a standardized output
     for every one.
    
    Question:
    
    In my scenario which one is the best to have "SQL query or function"?
    if i choose "function" i have to sacrifice the performance 
    if i choose "SQL query" i am not sure whether each and every developer querying the same way as it would be
    
    
    Sorry if it is a dumb question to ask.
    
    Thanks in advance
    phani

    hoek question: what happens if I have to choose between the SQL and function? (Assume that they do not accept to create views)

    If views are not accepted (which is very strange IMO), but you need some "standard object" which anyone can use, then you would choose to use a function instead of everyone having "their own motion.
    It is a compromise between maintaining standards and performance (call PL/SQL in SQL is generally to be avoided because of context switching, the other way around is OK).
    One of the advantages of a view: no problems with the settings you must enter but never going to use, you just choose the columns you need and there you go.
    Other: it is simple, plain and simple.
    It is easier to maintain.
    But everything depends on what your function returns.
    Maybe a REF CURSOR?

    Your question reminds me of this interesting discussion:

    http://asktom.Oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:672724700346558185

    Published by: hoek on July 1st, 2009 16:39 tyop

  • By commas in the SQL decode error function

    Hi all

    DB: 11.2.0.3.0


    I use the sub query to generate the file defined by the output in a file of waiting but it error with the following message:

    SQL > set of lines 100-page 50
    SQL > col 'USER_CONCURRENT_QUEUE_NAME' format a40.
    SQL > set off head
    SQL > spool /home/xyz/cmrequests.csv
    SQL > SELECT
    2 a.USER_CONCURRENT_QUEUE_NAME | ','
    3. a.MAX_PROCESSES | ','
    4. Sum (decode (b.PHASE_CODE, 'P', Decode (b.STATUS_CODE, 'Q', 1, 0), 0)) Pending_Standby | «, »
    5. Sum (decode (b.PHASE_CODE, 'P', Decode (b.STATUS_CODE, 'I', 1, 0), 0)) Pending_Normal | «, »
    6. Sum (decode (b.PHASE_CODE, 'R', Decode (b.STATUS_CODE, 'R', 1, 0), 0)) Running_Normal
    7 of FND_CONCURRENT_QUEUES_VL a, FND_CONCURRENT_WORKER_REQUESTS b
    where a.concurrent_queue_id = b.concurrent_queue_id AND b.Requested_Start_Date < = SYSDATE
    8 9 GROUP BY a.USER_CONCURRENT_QUEUE_NAME, a.MAX_PROCESSES;
    || Sum (decode (b.PHASE_CODE, 'P', Decode (b.STATUS_CODE, 'Q', 1, 0), 0)) Pending_Standby | «, »
    *
    ERROR on line 4:
    ORA-00923: THE KEYWORD not found where expected


    SQL > spool off;
    SQL >


    Expected results in the /home/xyz/cmrequests.csv coil

    Manager of the standard, 10, 0, 1, 0


    Thanks for your time!

    Kind regards

    Try under request

    SELECT USER_CONCURRENT_QUEUE_NAME. «, » || MAX_PROCESSES | «, » || Pending_Standby | «, » || Pending_Normal | «, » || Running_Normal
    DE)
    SELECT a.USER_CONCURRENT_QUEUE_NAME,
    a.MAX_PROCESSES,
    Sum (decode (b.PHASE_CODE, 'P', Decode (b.STATUS_CODE, 'Q', 1, 0), 0)) Pending_Standby,.
    Sum (decode (b.PHASE_CODE, 'P', Decode (b.STATUS_CODE, 'I', 1, 0), 0)) Pending_Normal,.
    Sum (decode (b.PHASE_CODE, 'R', Decode (b.STATUS_CODE, 'R', 1, 0), 0)) Running_Normal
    FND_CONCURRENT_QUEUES_VL a.,
    FND_CONCURRENT_WORKER_REQUESTS b
    WHERE a.concurrent_queue_id = b.concurrent_queue_id
    AND b.Requested_Start_Date<=>
    GROUP BY a.USER_CONCURRENT_QUEUE_NAME a.MAX_PROCESSES);

  • date function with logical operator does not...

    Hi all

    I saw table FINYEAR that having all the details of the fiscal year of the company. I have in my procedure according to user input identify current fiscal.

    Data in table FINYEAR...

    PATHDESCFDATELDATECIDCLOSINGYEAR
    April 1, 2010 to March 31, 201101/04/201031/03/2011BCDTRA0003H
    April 1, 2011 to March 31, 201201/04/201131/03/2012BCDTRA0003H
    April 1, 2012 to March 31, 201301/04/201203/31/2013BCDTRA0003H
    April 1, 2013 to 31 March 201401/04/201331/03/2014BCDTRA0003S
    March 31, 2015, 1 April 201401/04/201431/03/2015BCDTRA0003

    "I have two parameter in the procedure F_DATE = January 1, 2013 ', L_DATE = March 30, 2013.

    Above the entrance I must identify period are what financial year.

    Result must be this line... bcz F_DATE and L_DATE are with the fiscal year 2012-2013...

    April 1, 2012 to March 31, 201301/04/201203/31/2013BCDTRA0003H

    I try with the query below, but no luck... Please help in this regard

    Select * from finyear where

    Fdate < to_date('01/01/2013','DD/MM/RRRR')

    and ldate < to_date('30/03/2013','DD/MM/RRRR') and cid = "BCDTRA0003";

    Try this:

    SELECT * FROM finyear

    WHERE the to_date('01/01/2013','DD/MM/YYYY') BETWEEN fdate ldate AND

    AND to_date('30/03/2013','DD/MM/YYYY') BETWEEN fdate ldate AND

    AND cid = "BCDTRA0003";

  • String separated by commas to 'IN' operator in SQL query

    Hello

    The issue is that the "In" operator in the report query accepts values contained in the element of page Apex... 221,332,542.

    Is there a common solution for this problem?

    Thank you

    Patrick

    984146 wrote:

    The issue is that the "In" operator in the report query accepts values contained in the element of page Apex... 221,332,542.

    It's the common "variable list" model [anti-]. In

    select * from table where columnvalue in (7788, 7839, 7876)
    

    (7788, 7839, 7876)is a list of expressions and the predicate is evaluated as a membership condition.

    In

    select * from table where columnvalue in :P1_X
    

    :P1_Xis a scalar string, unable to contain multiple values.

    In a report of type APEX, a source report of the body of the PL/SQL function returning a SQL query with lexical substitution can be used to produce a "variable list:

    return 'select * from table where columnvalue in (' || :P1_X || ')';
    

    where P1_X contains less than 1000 values, has been disinfected to code SQL injectionand string values are properly cited.

    Some people suggest the following approach, that will work also in interactive APEX reports:

    select * from table where instr(':' || :P1_X || ':', ':' || columnvalue || ':') > 0
    

    However, it is underperforming because it eliminates the possibility of using the index optimizer or the size of the partition in the execution plan.

    See various elements in the list to ask Tom and imitating the channel to the table using sql features for effective solutions.

Maybe you are looking for