Better sql query.

hello all,
i am using 11g db, and have written a query which joins 4-5 tables and fetches data .these are big tables and query takes some time.
suppoes the tables are tab1 to tab5.
now i want to add another condition using tab6, which has2.5 milion records.
i have to see that the data fetched from the query does not have a matching record in tab6
eg:
filter condition is
and (tab3.col1,tab3.col2) not in (select tab6.col1, tab6.col2 from tab6)
i assume that this will iterate 2.5 million times for every row fetched from the main query .
is there a better way?
thanks

The Oracle optimiser is smart and has many ways of doing things. The query might iterate over the first set and look up an index on tab6 (col1, col2) but I think it is more likely to do another type of anti-join (hash or merge) because row by row lookups end up doing so much I/O. It will do its best to avoid scanning tab6 multiple times. With millions of rows, single full table scans are good. If your original query is estimated to only get a few thousand rows, and there is no index, I'd expect to see a hash anti-join with the database working out the original result set then using the hash anti-join to remove the rows that have a match.
You can get some idea by doing an explain plan on the proposed query, although the most accurate results come from running the query then using DBMS_XPLAN.DISPLAY_CURSOR to view the actual plan. In SQLPlus, set serverout off; alter session set statistics_level=ALL; run your query then select * from table(dbms_xplan.display_cursor(null, null, 'IOSTATS LAST'))
Another way of describing the query is
select ... from (current query) q
left outer join tab6 on tab6.col1 = tab3.col1 and tab6.col2 = tab3.col2
where tab6.col1 is null
That uses an outer join to find the cases where the row exists and then the where clause excludes those, keeping only the rows where there was no match. This sometimes gives a different plan.
Tell us your Oracle version, (to 4 places e.g. 11.2.0.3) at least, and try each query to see what it does.
regards,
David

Similar Messages

  • Better SQL Query for clients without boundaries?

    I've been using and modifying/experimenting with Chris Nackers' SQL query for missing boundaries (http://myitforum.com/myitforumwp/2011/12/07/sql-query-to-identify-missing-smsconfigmgr-boundaries/)
    below (changed to add aliases)--but this seems to mainly be showing us non-clients, as several computers that were indeed missing boundaries (using SCCM 2007 SP2 R3, and all our boundaries are protected, most are IP Range, a few IP Subnet, none AD Site) are
    not being listed, and everything in the listing has NULL SYS.Client0.
    Is there a better query to pinpoint this issue, or maybe using something (error code or log?) that would show computers that can't find a distribution point or some other evidence of not having a boundary?
    Thanks!
    SELECT DISTINCT SYS.Name0, SYS.Client0, IPA.IP_Addresses0, IPS.IP_Subnets0, SMSAS.SMS_Assigned_Sites0
    FROM dbo.v_R_System SYS
    LEFT OUTER JOIN dbo.v_RA_System_IPSubnets IPS ON SYS.ResourceID = IPS.ResourceID
    LEFT OUTER JOIN dbo.v_RA_System_IPAddresses IPA ON SYS.ResourceID = IPA.ResourceID
    LEFT OUTER JOIN dbo.v_RA_System_SMSAssignedSites SMSAS ON SYS.ResourceID = SMSAS.ResourceID
    LEFT OUTER JOIN dbo.v_RA_System_SystemOUName SOU ON SYS.ResourceID = SOU.ResourceID
    WHERE (SMSAS.SMS_Assigned_Sites0 IS NULL)
    AND (NOT (IPA.IP_Addresses0 IS NULL))
    AND (NOT (IPS.IP_Subnets0 IS NULL))
    AND SYS.Operating_System_Name_and0 LIKE 'microsoft%server%'
    ORDER BY IPS.IP_Subnets0, SYS.Name0

    I gotcha now... I think most people, myself included, rely on finding clients that are not assigned to determine if a boundary is missing. If you expect clients to not be assigned that's not going to work for you.
    WHERE (SMSAS.SMS_Assigned_Sites0
    IS NULL) 
    AND (NOT (IPA.IP_Addresses0
    IS NULL))
    AND (NOT
    (IPS.IP_Subnets0 IS
    NULL))
    = This is saying show me all clients not assigned but they do have an IP address and they do have a subnet discovered.
    In the case of CM12 it is actually possible for that not to work anyway because you can have separate boundaries for client assignment and content lookup.
    I am not aware of any query that can compare the IP address, AD Site and IP subnet from each client to what's configured in boundaries and find machines that do not fall into any boundary.
    John Marcum | http://myitforum.com/myitforumwp/author/johnmarcum/

  • CRVS2010 Beta - Edit Sql query at runtine

    Hello,
    I'm migrating an old application in delphi to C#. This application is able to change the Sql query at run time (without using RecordSelectionFormula) to add filtering in where clause. I want to do the same, but I didn't found any equivalent property, and I don't think it's possible to convert the query into RecordSelectionFormula's format (too complex).
    I can't modify rapports too btw.
    Any help ?
    Thanks,

    And then again:
                //Set the attributes for the logonPropsBag
                logonProps.Add("Database", "xtreme");
                logonProps.Add("DSN", "DSN Name");
                logonProps.Add("UseDSNProperties", "False");
                //Set the attributes
                QEProps.Add("Database DLL", "crdb_odbc.dll");
                QEProps.Add("QE_DatabaseName", "xtreme");
                QEProps.Add("QE_DatabaseType", "ODBC (RDO)");
                //Add the QE_LogonProperties we set in the logonProps Object
                QEProps.Add("QE_LogonProperties", logonProps);
                QEProps.Add("QE_ServerDescription", "Dwilliams1 - VAN-W-13-DWILLI");
                QEProps.Add("QE_SQLDB", "True");
                QEProps.Add("SSO Enabled", "False");
                newConnInfo.Attributes = QEProps;
                newConnInfo.UserName = "sa";
                newConnInfo.Password = "password";
                newConnInfo.Kind = CrConnectionInfoKindEnum.crConnectionInfoKindCRQE;
                newTbl.ConnectionInfo = newConnInfo;
                newTbl.CommandText = sql;
                newTbl.Name = "Command";
                //foreach(CrystalDecisions.ReportAppServer.DataDefModel.Table tbl in rcd.Database.Tables)
                // use the above line for more than one table if required, Also note the Table[0] index needs to be updated also.
                    //oldTbl = tbl.Clone(true);
                    rcd.DatabaseController.SetTableLocationEx(oldTbl,newTbl);
                    oldTbl =(CrystalDecisions.ReportAppServer.DataDefModel.Table) rcd.Database.Tables[0].Clone(true);
                    rcd.DatabaseController.SetTableLocationEx(oldTbl, newTbl);
                // save the report to a new folder
                rcd.SaveAs(rcd.DisplayName, "c:
    Updated
    ", 0);
    Thank you
    Don

  • Displaying a radio group in SQL QUERY report region

    Good morning everyone,
    I have a report in which a column - ORDER STATUS, will come in with a value of 1, 2 or 3...being order unfilled, order partially filled, or order filled, respectively.
    I would like to display the order status as a radio group on the report so that it will be easy to run down the column of radio buttons to see what is filled, etc.
    I've gone to the manual and checked the doco on HTMLDB_ITEM.RADIOGROUP. But the example given there is actually for CHECKBOX (is this an error?!?).
    I went to the forums and found nothing suitable.
    My region is an SQL QUERY. Can I display the STATUS as a radio group in the SELECT ?
    This is the question.
    Thankyou in anticipation. TC. 23/11/2004

    Tony,
    There may be better solutions, but here's what I was thinking:    create table orders (id number, status number, customer varchar(30))
        insert into orders (id,status,customer) values(1,1,'ACME')
        insert into orders (id,status,customer) values(2,2,'BENSON')
        insert into orders (id,status,customer) values(3,3,'CLARKE')
        commit
        Query Source
        select
          id "ORDER NUMBER",
          decode(status,
            1,htmldb_item.RADIOGROUP(1,status,'1','unfilled')||htmldb_item.RADIOGROUP(2,status,'2','partial','"disabled=true"')||htmldb_item.RADIOGROUP(3,status,'3','filled','"disabled=true"'),
            2,htmldb_item.RADIOGROUP(1,status,'1','unfilled','"disabled=true"')||htmldb_item.RADIOGROUP(2,status,'2','partial')||htmldb_item.RADIOGROUP(3,status,'3','filled','"disabled=true"'),
            3,htmldb_item.RADIOGROUP(1,status,'1','unfilled','"disabled=true"')||htmldb_item.RADIOGROUP(2,status,'2','partial','"disabled=true"')||htmldb_item.RADIOGROUP(3,status,'3','filled'))
          "STATUS",
          customer "Customer Name"
        from orders;Scott

  • Export to Excel from Report region (pl/sql returning sql query)

    Hello all,
    I have encountered an interesting problem. I have an HTMLDB application with a lot of sql reports coded straight inside the report region. In order to better organize my reports, I decided to
    1. make all my report regions of type "Pl/Sql function returning SQL query"
    2. create a package inside my database schema which houses all reports as pl/sql functions returning VARCHAR2, the string returned being the report query
    3. just calling "return package_name.function_name" from inside my report region of type "Pl/sql function returning SQL query".
    This technique seemed to work perfectly. The reports were being returned as expected. I was then asked to provide the "Export to Excel" capability to all my reports. This seemed like a piece of cake using HTML DB's "Export to Excel" extension. However, the "export to excel" does not function correctly when my reports are inside a package in the database. HTML DB tries to export but inside the excel spreadsheet, instead of seeing row data, I see:
    <pre>failed to parse SQL query:
    ORA-00936: missing expression
    <!-- select a.username, b.table_name, 'View Row Data' from schema_browser_user_list a, all_tables b where a.user_id = and a.username = b.owner order by b.table_name asc
    --!>
    </pre>
    I am building my query string inside of my package functions by using a combination of literal strings and concatenating them with some parameter values being passed in. It seems that the HTML DB engine which exports the report to excel does not properly understand the concatenation of variables as can be seen by the empty space to the right of the equal sign in the "a.user_id = " clause. Does anybody have any input as to whether this is a known issue or if I am doing something wrong? Thanks a lot for your time.
    - Kenny R.

    James,
    Thanks for the quick reply. I think you mis-understood what I'm doing. All I'm doing is creating packaged functions which return VARCHAR2. The VARCHAR2 that they return is the report query. With this technique, I no longer have to type the query into the HTML DB report region. Instead, I make the report region a "Pl/sql function returning sql query" and make the following call: return package_name.function_name(some_application_items passed in as parameters)
    This makes for a much more organized html db app. The problem is that the "export to excel" function does not correctly interpret the VARCHAR2 that my packaged functions are returning. Is this a better explanation? Thanks again for your time.
    - Kenny R.

  • How to pass parameter value as "where [fieldname] = [fieldvalue]" in sql query under query type in SSRS report?

    I am having trouble with passing dynamic string to sql query for executing SSRS reports.
    I am using oracle database and I want to pass where clause parameter as "where LAND_NR = 6" to my select query.
    For example: I want to execute Select * from employee :p_where.
    where p_where parameter holds value "where LAND_NR = 6"
    So it will treat as "Select * from employee where LAND_NR = 6" statement which will give me the list of records to display in my reports.
    But it's not taking correct sql command throwing an error as "SQLcommand not properly ended."
    How can I achieve this?

    You need to use dynamic sql
    But please keep in mind that since you're using Oracle you may be better off posting this in some Oracle forums
    This forum is specifically for SQL Server
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How to set fetchsize of sql Query when using Database Adapter.

    Hi All,
    I am using DatabaseAdapter to connect to database and retriving huge amount of data.For improvement in the performance I want to set the "fetchsize" of sql query. I know fetchsize can be preset in Java using Jdbc 2.0 API.Please let me know how to set this value in BPEL when using DBAdapter?
    Thanks
    Chandra

    I talked to the developer of the db adapter - and he told me this feature will be available in BPEL PM 10.1.3 (which is supposed to be production later this year, and a public beta soon). If this is an emergency I would recommend going throug Oracle support and have them file an enhancement for 10.1.2.0.2
    hth clemens

  • How to setup a query plan in effective at any time for SP or SQL query?

    I have a SP which include a group by SQL statement. It retrieve data from a couple of tables which are over 1G size,
    When I run this SP at first time, it take more than 5 minutes to get the result. then I run it again and again, Finally, it become very quick, I can get the result within second.
    Not sure why. I guess it is because of query plan.
    How to make it running at first time to get result within second? How to force a better best query plan in effective at first time to run the query?
    If the engine has better plan in memory, could it be lost at some point? because I have the complain from end user said some times it is fast, sometime it is very slow.
    How to resolve this problem?

    thanks, kevin. Here is the pesudo query( I modify table name as business rule from my company). you are right, mytab3 is a lookup table.
    Select d.stock,i.description,c.categoryname,
    Round(IsNull(Sum(d.qty),0),2) AS qty,
    From mytab1 d,mytab2 s,invent i,mytab3 c       
    Where
    d.stock != 'param1'
    And d.id1 = s.id1    --id1: univarchar(11)        
    And i.code = c.code   --code:univarchar(2)         
    And d.stock = i.stock  --stock: univarchar(12)           
    And i.code2 = d.code2  --code2: univarchar(2)
    And d.code2 = 'param2'
    And s.id2 = 'param3'   --id2: univarchar(6)
    Group By  c.categoryname,d.stock,i.description
    Order By d.stock
    here is the query plan when run this query:
    The command completed with no results returned
    QUERY PLAN FOR STATEMENT 1 (at line 1).
    Executed in parallel by coordinating process and 4 worker processes.
        STEP 1
            The type of query is SELECT (into Worktable1).
            GROUP BY
            Evaluate Grouped SUM OR AVERAGE AGGREGATE.
            Evaluate Grouped SUM OR AVERAGE AGGREGATE.
            Evaluate Grouped SUM OR AVERAGE AGGREGATE.
            Executed in parallel by coordinating process and 4 worker processes.
            FROM TABLE
                mytab2
                s
            Nested iteration.
            Index : ind_mytab2 _id2
            Forward scan.
            Positioning by key.
            Keys are:
                id2  ASC
            Executed in parallel with a 4-way hash scan.
            Using I/O Size 16 Kbytes for index leaf pages.
            With LRU Buffer Replacement Strategy for index leaf pages.
            Using I/O Size 16 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            FROM TABLE
                mytab1
                d
            Nested iteration.
            Index : ind_det_inv
            Forward scan.
            Positioning by key.
            Keys are:
                id1  ASC
            Using I/O Size 16 Kbytes for index leaf pages.
            With LRU Buffer Replacement Strategy for index leaf pages.
            Using I/O Size 16 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            FROM TABLE
                invent
                i
            Nested iteration.
            Using Clustered Index.
            Index : invent_pk
            Forward scan.
            Positioning by key.
            Keys are:
                stock  ASC
                code2  ASC
            Using I/O Size 2 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            FROM TABLE
                mytab3
                c
            Nested iteration.
            Table Scan.
            Forward scan.
            Positioning at start of table.
            Using I/O Size 2 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            TO TABLE
                Worktable1.
            Parallel work table merge.
        STEP 2
            The type of query is INSERT.
            The update mode is direct.
            Executed by coordinating process.
            Worktable2 created, in allpages locking mode, for ORDER BY.
            FROM TABLE
                Worktable1.
            Nested iteration.
            Table Scan.
            Forward scan.
            Positioning at start of table.
            Using I/O Size 8 Kbytes for data pages.
            With MRU Buffer Replacement Strategy for data pages.
            TO TABLE
                Worktable2.
        STEP 3
            The type of query is SELECT.
            Executed by coordinating process.
            This step involves sorting.
            FROM TABLE
                Worktable2.
            Using GETSORTED
            Table Scan.
            Forward scan.
            Positioning at start of table.
            Using I/O Size 8 Kbytes for data pages.
            With MRU Buffer Replacement Strategy for data pages.
    Total estimated I/O cost for statement 1 (at line 1): 1409882.
    The sort for Worktable2 is done in Serial

  • SQL query execution Issue

    Hi,
    Facing Database performance issue while runing overnight batches.
    Generate tfprof output for that batch and found some sql query which is having high elapsed time. Could any one please let me know what is the issue for this. It will also be great help if anyone suggest what need to be done as per tuning of this sql queries so as to get better responce time.
    Waiting for your reply.
    Effected SQL List:
    INSERT INTO INVTRNEE (TRANS_SESSION, TRANS_SEQUENCE, TRANS_ORG_CHILD,
    TRANS_PRD_CHILD, TRANS_TRN_CODE, TRANS_TYPE_CODE, TRANS_DATE, INV_MRPT_CODE,
    INV_DRPT_CODE, TRANS_CURR_CODE, PROC_SOURCE, TRANS_REF, TRANS_REF2,
    TRANS_QTY, TRANS_RETL, TRANS_COST, TRANS_VAT, TRANS_POS_EXT_TOTAL,
    INNER_PK_TECH_KEY, TRANS_INNERS, TRANS_EACHES, TRANS_UOM, TRANS_WEIGHT,
    TRANS_WEIGHT_UOM )
    VALUES
    (:B22 , :B1 , :B2 , :B3 , :B4 , :B5 , :B21 , :B6 , :B7 , :B8 , :B20 , :B19 ,
    NULL, :B9 , :B10 , :B11 , 0.0, :B12 , :B13 , :B14 , :B15 , :B16 , :B17 ,
    :B18 )
    call count cpu elapsed disk query current rows
    Parse 722 0.09 0.04 0 0 0 0
    Execute 1060 7.96 83.01 11442 21598 88401 149973
    Fetch 0 0.00 0.00 0 0 0 0
    total 1782 8.05 83.06 11442 21598 88401 149973
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    UPDATE /*+ ROWID(TRFDTLEE) */TRFDTLEE SET TRF_STATUS = :B2
    WHERE
    ROWID = :B1
    call count cpu elapsed disk query current rows
    Parse 635 0.03 0.01 0 0 0 0
    Execute 49902 14.48 271.25 41803 80704 355837 49902
    Fetch 0 0.00 0.00 0 0 0 0
    total 50537 14.51 271.27 41803 80704 355837 49902
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    DECLARE
    var_trans_session     invtrnee.trans_session%TYPE;
    BEGIN
    -- ADDED BY SHANKAR ON 08/29/97
    -- GET THE NEXT AVAILABLE TRANS_SESSION
    bastkey('trans_session',0,var_trans_session,'T');
    -- MAS001
    uk_trfbapuo_auto(var_trans_session,'UPLOAD','T',300);
    -- MAS001 end
    END;
    call count cpu elapsed disk query current rows
    Parse 0 0.00 0.00 0 0 0 0
    Execute 1 24191.23 24028.57 8172196 10533885 187888 1
    Fetch 0 0.00 0.00 0 0 0 0
    total 1 24191.23 24028.57 8172196 10533885 187888 1
    Misses in library cache during parse: 0
    Misses in library cache during execute: 1
    Optimizer goal: CHOOSE
    SELECT INNER_PK_TECH_KEY
    FROM
    PRDPCDEE WHERE PRD_LVL_CHILD = :B1 AND LOOSE_PACK_FLAG = 'T'
    call count cpu elapsed disk query current rows
    Parse 1 0.01 0.00 0 0 0 0
    Execute 56081 1.90 2.03 0 0 0 0
    Fetch 56081 11.07 458.58 53792 246017 0 56081
    total 112163 12.98 460.61 53792 246017 0 56081
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    ******************

    First off, be aware of the assumptions I'm making. The SQL you presented above strongly suggests (to me at least) that you have cursor for loops. If that's the case, you need to review what their purpose is and look to convert them into single statement DML commands. For example if you have something like this
    DECLARE
        ln_Count        NUMBER;
        ln_SomeValue    NUMBER;
    BEGIN
        FOR lcr_Row IN (    SELECT pk_id,col1,col2 FROM some_table)
        LOOP
            SELECT
                COUNT(*)
            INTO
                ln_COunt
            FROM
                target_table
            WHERE
                pk_id = lcr_Row.pk_id;
            IF ln_Count = 0 THEN
                SELECT
                    some_value
                INTO
                    ln_SomeValue
                FROM
                    some_other_table
                WHERE
                    pk_id = lcr_Row.col1
                INSERT
                INTO
                    target_table
                    (   pk_id,
                        some_other_value,
                        col2
                VALUES
                    (   lcr_Row.col1,
                        ln_SomeValue,
                        lcr_Row.col2
            ELSE
                UPDATE
                    target_table
                SET
                    some_other_value = ln_SomeValue
                WHERE
                    pk_id = lcr_Row.col1;
            END IF;
        END LOOP;
    END;                            it could be rewritten as
    DECLARE
    BEGIN
        MERGE INTO target_table b
        USING ( SELECT
                    a.pk_id,
                    a.col2,
                    b.some_value
                FROM
                    some_table a,
                    some_other_table b
                WHERE
                    b.pk_id = a.col1
               ) e
        ON (b.pk_id = e.pk_id)
        WHEN MATCHED THEN
          UPDATE SET b.some_other_value = e.some_value
        WHEN NOT MATCHED THEN
          INSERT (  b.pk_id,
                    b.col2,
                    b.some_other_value)
          VALUES(   b.pk_id,
                    b.col2,
                    b.some_value);
    END;It's going to take a bit of analysis and work but the fastest and most scalable way to approach processing data is to use SQL rather than PL/SQL. PL/SQL data processing i.e. cursor loops should be an option of last resort.
    HTH
    David

  • What SQL query I need for this?

    I need to execute a SQL query but I don't know how.
    To illustrate it, please take a look at some example data:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31
        1         2004-12-31
        1         2004-11-31
        2         2005-12-31
        2         2005-11-31
        2         2005-10-31
        2         2005-09-31 This is a piece of the sales data for the articles (sales history).
    Lets assume that today is the date 2005-12-31.
    Two requirements for the query:
    1. Get the sales data for the last 12 months.
    2. Get only the sales data for articles where there is sales data since at least 6 months.
    The result in my example should look like this:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31 What is the SQL which I need to accomplish this query?

    To get all the information from the last 12 months
    you will have to use date manipulation.
    SELECT add_months(sysdate, -12) from
    dual;This gives you the date 12 months ago.
    So you will have to select your date between then and
    the current date.If I do this I will get this data:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31
        2         2005-12-31
        2         2005-11-31
        2         2005-10-31
        2         2005-09-31 But I want this data:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31 I am no native English speaker. What didn't you understand in the two requirements?
    Here are my two requirements for the query:
    1. Get the sales data for the last 12 months.
    2. But get ONLY the sales data for articles where there is sales data since AT LEAST 6 months.
    The result can contain as many IDs as you want if the two requirements are met. Its not a trivial SQL statement for me. Please remember that the above data are only for illustration. They are just an example.
    There should be a SQL statement for this.
    Please tell me if you don't understand my problem. I will try to explain it in a better way if I can.

  • SQL Query in Prompt

    Hi,
    in "Show" section of my prompt i've following SQL Query:
    select Country."Company Description" from Prototype where Country."Country Code Company GOAL Code" IN
    (Select Entity_Relationship.Company from Prototype where Entity_Relationship.Parent
    IN (Select Entity. "HFM Entities" from Prototype where Entity.Description ='@{Entity}'))
    UNION
    select Country."Company Description" from Prototype where Country."Country Code Company GOAL Code" IN
    (Select Entity_Relationship.Company from Prototype where Entity_Relationship.Child
    IN (Select Entity. "HFM Entities" from Prototype where Entity.Description ='@{Entity}'))
    It returns Company Descriptions where id equal presentation variable. And it works fine. Now i want that if query returns an empty resultset, it must returns a default string 'Not Defined Country'. How can i modify my query?
    Thanks
    Giancarlo

    Hi,
    it doesn't work because presentation variable will be always filled. The whole query can return an empty resultset, but presentation variable will have always a value. I try to explain better...
    My query (composed by two queries linked by Union clause) can return one or more Country."Company Description" records, but it can return even 0 rows. Now when it returns 0 rows my prompt will be an empty prompt (no choices). Now i want that if it so, query must return a default string "Not defined Country". In my opinion i must add to my query other clauses like EXISTS, NOT EXISTS, IN, NOT IN, or case when clause. But how?
    Thanks
    Giancarlo

  • Sql query to seperate character and number data in a column

    Hi,
    We have a test table on 10.2.0.4 db as below;
    10:44:34 TEST:WAULT > desc t;
    Name Null? Type
    EMP VARCHAR2(10)
    10:43:18 TEST:WAULT > select * from t;
    EMP
    JOHN
    7281
    TOM
    7852145
    BNPPARIBAS
    9862354
    Mindcraft
    875
    INFINITY
    78998775
    01234
    EMP
    0
    -123
    -856359
    SCOTT
    -657
    16 rows selected.
    The question is; we need to segregate the character data and numerical data in the EMP field, using sql query.
    Plz suggest as to how we can achieve this.
    Also, plz suggest how the use of reqexp can be made in this to achieve the same.
    Thanks,
    Rahul

    >
    Hi,
    EMP
    JOHN
    7281
    TOM
    7852145
    The question is; we need to segregate the character data and numerical data in the EMP field, using sql query.
    Plz suggest as to how we can achieve this.Check out the CAST function
    http://download.oracle.com/docs/cd/B12037_01/server.101/b10759/functions015.htm
    However, I would have to ask why on earth you're doing this - it would, IMHO, be
    much better to redesign your app. It looks like you have an EAV problem
    (AKA MUCK or OTLT) Google Joe Celko and these terms.
    Paul...
    Rahul

  • Oracle Sql Query issue Running on Different DB Version

    Hello All,
    I have come into situation where we are pruning sql queries on different DB version of Oracle and have performance issue. Let me tell you in brief and i really appreciate for your prompt response as its very imperative stuff.
    I have a query which is running on a DB of version 7.3.4 and it takes around 30 mins where as the same query when run on 8i it takes 15sec., its a huge difference. I have run the statistics to analyze on 7.3 and its comparatively very high. Question here is, the sql query trys to select data from same schema table and 2 tables from another DB using DB link and 2 other tables from another DB using DB link.So,how can we optimize this stuff and achieve this run as same time as 8i DB in 7.3. Hope i am clear about my question, Eagerly waiting for your replies.
    Thanks in Advance.
    Message was edited by:
    Ram8

    Difficult to be sure without any more detailed information, but I suspect that O7 is in effect copying the remote tables to local temp space, then joining; 8i is factoring out a better query to send to the remote DBs, which does as much work as possible on the remote DB before shipping remaining rows back to local.
    You should be able to use EXPLAIN PLAN to identify what SQL is being shipped to the remote DB, If you can't (and it's been quite a while since I tried DB links or O7) then get the remote DBs to yourself, and set SQL_TRACE on for the remote instances. Execute the query and then examine the remote trace files, And don't forget to turn off the tracing when you're done.
    Of course it could just be that the CBO got better,,,
    HTH - if not, post your query and plans for the local db, and the remote queries.
    Regards Nigel

  • Question about using objects in SQL query.

    I had posted this question in the SQL/PLSQL forum but I guess nobody took the time to understand exactly what I am asking so I decided to try here hoping to get the answer. So here is the thing:
    I have created generic object type "tree" - the constructor takes as a parameter sql query which returns "node_id" and "parent_node_id" - this is all we need to have a tree. The object has all related to a tree structure member functions and one of them is "oldest_relative" (the tree may not be fully connected - it may be more like a set of many trees, so it's not necessary all nodes to have the same root).
    I also have departments table with the following fields: department_id, parent_department_id, department_name,...
    all records in the table w/out parent_departments (parent_department_id is null) are considered divisions.
    Now if I run the following query:
    SELECT "DEPARTMENT_ID", "PARENT_DEPARTMENT_ID", "DEPARTMENT_NAME", tree('select department_id "node_id", parent_department_id "parent_node_id" from departments').oldest_relative("DEPARTMENT_ID") "DIVISION_ID" FROM departments
    my question is: Is the tree object created for every row or does Oracle somehow caches the object since the object itself is not changing but only the parameter for the oldest_relative member function.
    The table only has a few hunderd records and I can't see much of a difference in the execution time btw the query above and query like this:
    SELECT "DEPARTMENT_ID", "PARENT_DEPARTMENT_ID", "DEPARTMENT_NAME", b.t.oldest_relative("DEPARTMENT_ID") "DIVISION_ID"
    FROM departments left join (select tree('select department_id "node_id", parent_department_id "parent_node_id" from departments') t from dual) b on 1 = 1
    where the object is clearly created just ones. (there is probably a better way to do it instead of this join)
    Pls elaborate
    George

    Not exactly sure what the question is...
    As I understand, you are comparing the following two constructor calls:
    +select..  tree('select department_id "node_id", parent_department_id "parent_node_id" from departments').oldest_relative("DEPARTMENT_ID") ... FROM ...+
    +select tree('select department_id "node_id", parent_department_id "parent_node_id" from departments') ... FROM dual+
    These calls are the same (besides the 1st one doing an immediate implicit call to a method of the object being constructed). The number of times these are being called depends on the number of times this SQL projection is applied - and that is determined by the number of rows being projected by the SELECT.
    The latter one is against DUAL which only has a single row. So that constructor is only called once. The former can be against multiple rows. Obviously a single pass through a data set is desirable - which means that the sub-select (use by the constructor) should ideally only be executed once and makes the 2nd method more desirable.
    However, I'm having a hard time understanding why the class and constructor are at all needed. Why pull data from a SQL table into PL memory? As that is where the class will need to cache and store the results of that construction parameter SQL SELECT. And once in PL memory, how does the object effectively access, search and use this cached data?
    PL memory is expensive. It is not sharable.
    PL data structures are primitive - these cannot be compared to SQL structures in the form of tables and columns that can be stored in a number of physical ways (index tables, hash tables, partitioned tables, clustered tables, etc). Cannot be indexed like SQL structures using B+tree, bitmap, function and other indexing methods. Cannot be sorted, grouped, analysed, filtered, etc like SQL structured data.
    It makes very little sense to read SQL data into a class and then deal with that data, cached in expensive PL memory, using primitive PL structures.
    And the same would be true if Java or C# was used. The best place for data is inside the SQL engine. That is the most superior environment for data. It can processes more data, scale better, perform better and offer more flexibility, than pulling data from it and then crunch that data using PL or Java or C#.

  • Parse User Pasted Text and use in SQL query

    I am trying to take some user pasted text (typically would come from Excel) and parse those values and put into a query.
    text area:
    ":P11_text"
    query:
    "select *
    from table
    where column in :P11_text;"
    I have tried some variations of replace and translate in order to parse that list of values...something like: translate(:P11_text, chr(10)||chr(13), ',' ).....and many variations of this.
    I have been able to replace the end of lines with the commas, but it appears that I am not getting my single quotes captured, even when trying to force them in. The best attempt returned single quotes and commas in between values but not at the beginning and end of the list of values.
    I would bet that there is an easy way to accomplish this or an easy way to accomplish the requirement in a different way altogether.
    Please point me in the right direction.

    I finally got this one figured out!
    create or replace type myTableType as table
    of varchar2(4000)
    create or replace
    function in_list( p_string in varchar2 ) return myTableType
    as
    l_string long default p_string || ',';
    l_data myTableType := myTableType();
    n number;
    begin
    loop
    exit when l_string is null;
    n := instr( l_string, ',' );
    l_data.extend;
    l_data(l_data.count) :=
    ltrim( rtrim( substr( l_string, 1, n-1 ) ) );
    l_string := substr( l_string, n+1 );
    end loop;
    return l_data;
    end;
    --The SQL Query is:
    select *
    from t wher c in (select *
    from THE
    ( select cast( in_list(translate(:p10_prolist,chr(10)||chr(13),',')) as
    mytableType ) from dual ) a);
    --Working like a champion!!!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • HT4623 do install new iPhone 5 as backup or new?

    When connecting to iTunes for the first time, do I choose install as new iPhone or as restore from backup?

  • Links in Signature's

    Hi Everyone, I am posting this thread, as more of a voting forum wherein we take a call on whether links after signatures should or should not be allowed. For e.g - when a person signs after writing his reply or giving a answer he can put a signature

  • The way Aperture renders my Nikon RAW (NEF) files look different than...

    The was Aperture renders my NEF files looks different than NX... Ok so I use all the in camera setting/tools to the best of abilities to try and cut my editing down as much as possible but when shooting RAW I end up having to tweak every images to ge

  • JMS - Useful from an international point of view?

    Hi everyone, I was wondering if JMS could be useful from a legislative point of view. I mean could it be useful when two companies situated in different countries communicate? Does JMS make this communication easier/better in any way? Hope someone is

  • Calling portal page

    Is there an API call to call a certain portal page? The only way i've found a way of doing this is using the following URL: click here Where _pageid is different for all pages. This is not very clever in case i decide to change the form at a later st