SQL - Query rewrite ?

Hi
I have this query
SELECT a.col1,
a.col2,
a.col3,
a.col4
FROM table1 a
WHERE a.id = (SELECT MAX (id)
FROM table1
WHERE table1.datecol <= p_date AND table1.col5 = p_number);
This is a cursor in a function so p_date and p_number are in parameters.
In the example above table1 contains abot 300 million rows, and the query does 2 scans
of the table1.
Is there anyway to rewrite this SQL statment with one access only ?

Both query will not give the same results
WITH table1 AS
(select 1 id, 1 col1, 1 col2, 1 col3, 1 col4, 1 col5, to_date('01/01/2011','dd/mm/yyyy') datecol from dual
union
select 1 id, 2 col1, 2 col2, 2 col3, 2 col4, 2 col5, to_date('02/01/2011','dd/mm/yyyy') datecol from dual
union
select 3 id, 3 col1, 3 col2, 3 col3, 3 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
union
select 4 id, 4 col1, 4 col2, 4 col3, 4 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
SELECT a.col1,
a.col2,
a.col3,
a.col4
FROM table1 a
WHERE a.id = (SELECT MAX (id)
FROM table1
WHERE table1.datecol <= to_date('03/01/2011','dd/mm/yyyy')
AND table1.col5 = 3);
WITH table1 AS
(select 1 id, 1 col1, 1 col2, 1 col3, 1 col4, 1 col5, to_date('01/01/2011','dd/mm/yyyy') datecol from dual
union
select 1 id, 2 col1, 2 col2, 2 col3, 2 col4, 2 col5, to_date('02/01/2011','dd/mm/yyyy') datecol from dual
union
select 3 id, 3 col1, 3 col2, 3 col3, 3 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
union
select 4 id, 4 col1, 4 col2, 4 col3, 4 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
SELECT * FROM
(SELECT
a.id,
max(a.id) over (partition by a.id order by a.id) maxid,
a.col1,
a.col2,
a.col3,
a.col4,
a.datecol,
a.col5 
FROM table1 a)
WHERE datecol <= to_date('03/01/2011','dd/mm/yyyy')
    AND col5 =3    
    AND id = maxid;Best regards
Mohamed Houri

Similar Messages

  • SQL Query rewrite, remove ORDER BY clause

    Hello,
    we've just installed a proprietary application which uses an Oracle 11.2.0.2 RAC database. We've seen that one of the auto-generated application's queries
    has poor performance (3-5 minutes for results), the query does a SELECT and at the end it uses an ORDER BY clause. If we remove the ORDER BY clause
    the query returns the results in less than 5 seconds. Unfortunately, we can't re-write the query in the application since we don't have any access to it and
    i was wondering if there is a way to rewrite the specific query from the database.
    We've already seen the SQL Patch but we can change only the hints of the query so we can't remove the ORDER BY clause from it. From what we've seen
    outlines also change only the hints and not the actual sql statement.
    Is there a way to rewrite the specific query from the database ?
    thanks in advance,
    Giannis

    Maybe DBMS_ADVANCED_REWRITE can help but this a SQL question than has very likely nothing to do with RAC.
    See http://www.oracle-base.com/articles/10g/dbms_advanced_rewrite.php.

  • Parsing and rewriting an SQL query

    Hi all,
    I need to rewrite bits of a valid PL/SQL query. In order to do so, I need semantic information about the query, such as "what are the table names columns are being selected from" or "do aggregate functions in a select provide column alias in order to use the query in +CREATE TABLE AS+ ...".
    Is it possible to somehow "ask" the Oracle parser for those bits of semantic info? I am using 9i.
    E.g.
    select X.ID, Y.NAME, SUM(ABS(Y.VALUE))
    from
    TABLE_X X,
    (select NAME, VALUE from TABLE_Z where DATE_STR = '20090101') Y
    where
    will become
    select X.ID, Y.NAME, SUM(ABS(Y.VALUE)) COL1
    from
    TABLE_X prefix. X,
    (select NAME, VALUE from prefix. TABLE_Z where DATE_STR = '20090101') Y
    where
    ...

    Thanks for your answers (which, unfortunately, do not give much hope)!
    +..so unfortunately you won't be able to use the 11g method introduced here (Anyhow still undocumented!).+
    Yes, that's very disappointing. I actually added the "has to be 9i compatible" remark after I found out the XML dump does not work on our servers - and read the manual page to realize why that's the case.
    I think you'd need to write your own, which will be extremely difficult and hard to maintain.*
    There is a BNF grammar of PL/SQL (homebrew, apparently - so no guarantees): http://www.antlr.org/grammar/1107752678378/PLSQLGrammar.g
    Now, if I only knew practical stuff about lexers and parsers and abstract syntax trees...

  • Rewrite sql query

    Hello,
    I need to rewrite this SQL query to give the same result, but in more resorcefull manner.
    Probably using aggregation, but I am not sure.
    Can somebody give me a head start.
    desc resource_bundles
    Name          Null     Type               
    LOCALE        NOT NULL CHAR(5)            
    BUNDLE_NAME   NOT NULL VARCHAR2(32)       
    RESOURCE_NAME NOT NULL VARCHAR2(64)       
    VALUE_STRING           VARCHAR2(2048 CHAR)
    select a.bundle_name,a.resource_name, a.value_string as Czech,(select b.value_string
                                             from resource_bundles b
                                             where b.bundle_name = a.bundle_name
                                             and b.resource_name = a.resource_name
                                             and b.locale = 'en_US'
                                            )as English,
                                             (select c.value_string
                                             from resource_bundles c
                                             where c.bundle_name = a.bundle_name
                                             and c.resource_name = a.resource_name
                                             and c.locale = 'ru_RU'
                                             ) as Russian,
                                             (select d.value_string
                                             from resource_bundles d
                                             where d.bundle_name = a.bundle_name
                                             and d.resource_name = a.resource_name
                                             and d.locale = 'it_IT'
                                            ) as Italian
    from resource_bundles a
    where a.locale = 'cs_CZ';Thank you
    Edited by: BluShadow on 15-Apr-2011 12:20
    added {noformat}{noformat} tags                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    It is always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    Also see the third post in this thread:
    {thread:id=2174552}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • A table is 'stuck' in the Discoverer SQL query after rewriting query.

    Hi,
    I'm using Discoverer 10.1.2.2 on an Oracle 9.2.0.6.0 DB.
    I've taken an existing Work Book and modified it. I've removed several fields as well as their table from the 'Selected Items' Window. I've also removed any references to all fields in that table in all Calculations and Conditions.
    Yet when I pull the SQL from the View: SQL Inspector That table still shows up and well as the join to it and a field from that table that I'm no longer using shows up as a field in the query. I'm not sure where else to check or what else to to do get this table out of this SQL query.
    Does anyone have any suggestions?

    Hi
    This can happen when someone has drilled inside a worksheet and saved the worksheet. The original or drilled to items are remembered,sometimes long after the drill item has been dispensed with. When this happens typically the only way to remedy the situation is to rebuild the worksheet from scratch.
    Before you get into that you do need to do one final scour to make sure that there is absolutely nothing in your worksheet that could cause the folder to be used. It could be in a long forgotten calculation. Sometimes when the only way to get from one folder to another one has to go via an intermediate folder by pulling any old item and then removing the item later. The folder willstill be used though. Could this be happening here?
    If you can rule out everything from the above paragraph then I am sorry to say but it sounds like you may have to rebuild from scratch.
    Best wishes
    Michael

  • How to modify a SQL query?

    Hi all,
    I am using Crystal Reports version 10. I have a number of reports that have been written by a software vendor wherby the name of the database they were connected to when the report was written is coded into the FROM command of the reports SQL query, eg "GCUK_2" in the of the SQL snippet below.
    SELECT "Clients"."NAME", "Quotes"."QUOTE_ID", "Quote_Items"."UPRICE", "Quote_Items"."QTY", "Quote_Items"."UOM", "Quote_Items"."QUSAGE_ID", "Report_Control"."QUSAGEID", "Quote_Items"."STANDARD", "Quote_Items"."SECT_FLAG", "Quote_Items"."DISPORDER", "Quotes"."DESCRIPT", "Report_Control"."SECT_NAME", "Quote_Items"."CNT", "Category_and_Type"."TYPEDESC", "Quote_Items"."DESCRIPT", "Report_Control"."DISP_SORT"
    FROM   ((("GCUK_2"."schedwin"."QTE_CTRL" "Report_Control" INNER JOIN "GCUK_2"."schedwin"."QUSAGE" "Quote_Items" ON "Report_Control"."QUSAGEID"="Quote_Items"."QUSAGE_ID") LEFT OUTER JOIN "GCUK_2"."schedwin"."QUOTES" "Quotes" ON
    I have tried setting the Datasource Location, but it doesn't change the query at all. I have read on another forum that you can generate another SQL query using the Database Expert, Current Connections, then right click the Add Command for the database you want to create a SQL command. Is this the only way to update the database names in the query?
    Thanks,
    Scott.

    Hi Sourashree,
    Thanks for that. All the reports were created by the vendor using tables as opposed to the command object. I would have thought that changing the datasource would automatically cause Crystal to rewrite the SQL query syntax, but this doesn't appear to be the case.
    Yes, I've noticed that modifying the record selection will change the sql query. The only way I can see to change the database name in the query is to change to the desired databsource and then remove and re-insert the tables, which will then update the query with the correct name. However, this seems to be a convoluted way of changing the db name in the query.

  • SQL Query produces different results when inserting into a table

    I have an SQL query which produces different results when run as a simple query to when it is run as an INSERT INTO table SELECT ...
    The query is:
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      The INSERT INTO code:
    TRUNCATE TABLE applicant_summary;
    INSERT /*+ APPEND */
    INTO     applicant_summary
    (  account_number
    ,  main_borrower_status
    ,  num_apps
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      When run as a query, this code consistently returns 2 for the num_apps field (for a certain group of accounts), but when run as an INSERT INTO command, the num_apps field is logged as 1. I have secured the tables used within the query to ensure that nothing is changing the data in the underlying tables.
    If I run the query as a cursor for loop with an insert into the applicant_summary table within the loop, I get the same results in the table as I get when I run as a stand alone query.
    I would appreciate any suggestions for what could be causing this odd behaviour.
    Cheers,
    Steve
    Oracle database details:
    Oracle Database 10g Release 10.2.0.2.0 - Production
    PL/SQL Release 10.2.0.2.0 - Production
    CORE 10.2.0.2.0 Production
    TNS for 32-bit Windows: Version 10.2.0.2.0 - Production
    NLSRTL Version 10.2.0.2.0 - Production
    Edited by: stevensutcliffe on Oct 10, 2008 5:26 AM
    Edited by: stevensutcliffe on Oct 10, 2008 5:27 AM

    stevensutcliffe wrote:
    Yes, using COUNT(*) gives the same result as COUNT(1).
    I have found another example of this kind of behaviour:
    Running the following INSERT statements produce different values for the total_amount_invested and num_records fields. It appears that adding the additional aggregation (MAX(amount_invested)) is causing problems with the other aggregated values.
    Again, I have ensured that the source data and destination tables are not being accessed / changed by any other processes or users. Is this potentially a bug in Oracle?Just as a side note, these are not INSERT statements but CTAS statements.
    The only non-bug explanation for this behaviour would be a potential query rewrite happening only under particular circumstances (but not always) in the lower integrity modes "trusted" or "stale_tolerated". So if you're not aware of any corresponding materialized views, your QUERY_REWRITE_INTEGRITY parameter is set to the default of "enforced" and your explain plan doesn't show any "MAT_VIEW REWRITE ACCESS" lines, I would consider this as a bug.
    Since you're running on 10.2.0.2 it's not unlikely that you hit one of the various "wrong result" bugs that exist(ed) in Oracle. I'm aware of a particular one I've hit in 10.2.0.2 when performing a parallel NESTED LOOP ANTI operation which returned wrong results, but only in parallel execution. Serial execution was showing the correct results.
    If you're performing parallel ddl/dml/query operations, try to do the same in serial execution to check if it is related to the parallel feature.
    You could also test if omitting the "APPEND" hint changes anything but still these are just workarounds for a buggy behaviour.
    I suggest to consider installing the latest patch set 10.2.0.4 but this requires thorough testing because there were (more or less) subtle changes/bugs introduced with [10.2.0.3|http://oracle-randolf.blogspot.com/2008/02/nasty-bug-introduced-with-patch-set.html] and [10.2.0.4|http://oracle-randolf.blogspot.com/2008/04/overview-of-new-and-changed-features-in.html].
    You could also open a SR with Oracle and clarify if there is already a one-off patch available for your 10.2.0.2 platform release. If not it's quite unlikely that you are going to get a backport for 10.2.0.2.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Problem using alias field names in a sql query

    Hello,
    I have a question regarding a simple Oracle database SQL query writeup:
    In the following (badly written but properly working) SQL query:
    Query 1:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    (soe.field5 - (soe.field2 + soe.field3)) as field6,
    (select comp.parValue*soe.field7
    from
    CompTable comp) as parValue,
    (select soe.field8 - (comp.parValue*soe.field7+ soe.field9)
    from
    CompTable comp) as field10
    from
    SomeTable soe
    PROBLEM 1:
    I am re writing the code (soe.field2 + soe.field3) to get the alias field4 or column name field4 that I have created on the fly in the previously for use with the following fields. Can't I rewrite the query as follows. There is something simple missing!
    Query 2:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    soe.field5 - field4 as field6, <<< field4 does not work here
    (select
    comp.parValue*soe.field7
    from
    CompTable comp) as parValue,
    (select
    soe.field8 - (comp.parValue*soe.field7+ soe.field9)
    from
    CompTable comp) as field10
    from
    SomeTable soe
    PROBLEM 2:
    Similar to the above problem, I was thinking to get a field parValue out of the CompTable table and re-use many times rather than the code shown in Query 1:
    Query 3:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    soe.field5 - field4 as field6,
    soe.field7* (select comp.parValue from CompTable comp) as parValue1,
    soe.field8 - (parValue1*soe.field7+ soe.field9) as field10      <<<< parvalue1 does not work here
    parValue1*soe.field9 as TaxCondition               <<<< parvalue1 does not work here
    from
    SomeTable soe
    See that the query becomes so simple, but the above query does not work. There is something fundamentally wrong in my usage of the alias field names in creating other fields. The Query1 seems to be the only working option but its very slow as I am redoing and re-writing the whole code again and again to get the parValue field out of the CompTable table for use to create many other fields.
    I will appreciate if you can guide me in the right direction on this issue.
    Thanks and Regards
    Rama

    SELECT tmp.contract_no, tmp.Actual, tmp.Actual - tmp.NbHours
    FROM ( SELECT t.contract_no, sum(l.hrs) AS Actual, (c.labour_hours * c.labour_progress_per) / 100 AS NbHours
    FROM TASK_DELEGATION t
    INNER JOIN COST_CODE c
    ON t.cost_code = c.cost_code AND t.contract_no = c.contract_no AND t.is_inactive=0
    INNER JOIN Labour.dbo.LABOURALLOT l
    ON l.contractNo = c.contract_no AND l.costcode = c.cost_code AND l.pm = 'N'
    GROUP BY t.contract_no, c.labour_hours, c.labour_progress_per
    ) tmp

  • Are Cube organized materialized view with Year to Date calculated measure eligible for Query Rewrite

    Hi,
    Will appreciate if someone can help me with a question regarding Cube organized MV (OLAP).
    Does cube organized materialized view with calculated measures based on time series  Year to date, inception to date  eg.
    SUM(FCT_POSITION.BASE_REALIZED_PNL) OVER (HIERARCHY DIM_CALENDAR.CALENDAR BETWEEN UNBOUNDED PRECEDING AND CURRENT MEMBER WITHIN ANCESTOR AT DIMENSION LEVEL DIM_CALENDAR."YEAR")
    are eligible for query rewrites or these are considered advanced for query rewrite purposes.
    I was hoping to find an example with YTD window function on physical fact dim tables  with optimizer rewriting it to Cube Org. MV but not much success.
    Thanks in advance

    I dont think this is possible.
    (My own reasoning)
    Part of the reason query rewrite works for base measures only (not calc measures in olap like ytd would be) is due to the fact that the data is staged in olap but its lineage is understandable via the olap cube mappings. That dependency/source identification is lost when we build calculated measures in olap and i think its almost impossible for optimizer to understand the finer points relating to an olap calculation defined via olap calculation (olap dml or olap expression) and also match it with the equivalent calculation using relational sql expression. The difficulty may be because both the olap ytd as well as relational ytd defined via sum() over (partition by ... order by ...) have many non-standard variations of the same calculation/definition. E.g: You can choose to use or choose not to use the option relating to IGNORE NULLs within the sql analytic function. OLAP defn may use NASKIP or NASKIP2.
    I tried to search for query rewrite solutions for Inventory stock based calculations (aggregation along time=last value along time) and see if olap cube with cube aggregation option set to "Last non-na hierarchical value" works as an alternative to relational calculation. My experience has been that its not possible. You can do it relationally or you can do it via olap but your application needs to be aware of each and make the appropriate backend sql/call. In such cases, you cannot make olap (aw/cubes/dimensions) appear magically behind the scenes to fulfill the query execution while appearing to work relationally.
    HTH
    Shankar

  • Pl/sql function body returning SQL query - Print function

    Hello all,
    I have pl/sql function body returning SQL query for my reports for my new project that I am developing. We dont have any BI tool or anything for APEX so we use Oracle reports to get the same reports to be printed in PDF format. I had been using SQL function for Reports all these days and grabbing the data using SQL query was easy in Oracle reports. But this time we had atleast 8 fields in search criteria and hence I thouhgt PL/sql function body returning SQL query could be something easy to handle that scenario. We have 11 such reports in our project. Now when we tried to use the same PL/sql function to oracle reports , I was told by one of our Oracle reports expert, that we have to write it into functions and use it in SQL query to get the Reports in Oracle reports. Is there any Easy way to convert the same Pl/SQL function or get a PDF format of the same report in APEX without going thru the much pains of rewriting the whole SQL Query.
    thank you
    Devisri

    Hi,
    give this a go.
    I can't test it as I don't have the tables in my schema.
    create or replace package MK_TEST_PF is
    -- Author  : MK
    -- Created : 21/06/2010 16:30:19
    -- Purpose : FOR LUCY_DISCOVER
    -- Public type declarations
    /*     -- just guess the table row types.....
         -- otherwise it won't compile
         type test_rec is record
              (INV REP.inv%type
              ,cNUMBER REP.cNUMBER%type
              ,OPENDATE REP.OPENDATE%type
              ,TARGETDATE REP.ESTCOMPLETE%type
              ,DATECLOSED REP.COMPLETED%type
              ,STATUS REP.STATUS%type
              ,cCODE REP.cCODE%type
              ,line varchar2(4000)
              ,SIGc varchar2(4000)
              ,CLASS REP.CLASS%type
              ,SUMM REP.SUMM%type
              ,AREA REP.AREA%type
         type test_rec is record
              (INV varchar2(4000)
              ,cNUMBER varchar2(4000)
              ,OPENDATE varchar2(4000)
              ,TARGETDATE varchar2(4000)
              ,DATECLOSED varchar2(4000)
              ,STATUS varchar2(4000)
              ,cCODE varchar2(4000)
              ,line varchar2(4000)
              ,SIGc varchar2(4000)
              ,CLASS varchar2(4000)
              ,SUMM varchar2(4000)
              ,AREA varchar2(4000)
         type test_tab is table of test_rec;
    -- Public constant declarations
    -- Public variable declarations
    -- Public function and procedure declarations
    end MK_TEST_PF;
    create or replace package body MK_TEST_PF is
    -- Private type declarations
    -- Private constant declarations
    -- Private variable declarations
    -- Function and procedure implementations
         function get_query_f
              (p_inv VARCHAR2 := UPPER(v('P44_INV'))
              ,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
              ,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
              ,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
              ,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
              ,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
              ,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
              ,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
              ,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
              ,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
              ,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
              ,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
              return varchar2
         is
              v_sql VARCHAR2(5000);
         --     v_inv VARCHAR2(100);
         --     v_reg VARCHAR2(100);
         --     v_proarea VARCHAR2(100);
         --     v_status VARCHAR2(100);
         --     v_SIG VARCHAR2(100);
         --     v_disp VARCHAR2(100);
         --     v_coding VARCHAR2(100);
         --     v_inc_sum VARCHAR2(4);
         --     v_word VARCHAR2(4000);
              v_wildcard VARCHAR2(2000);
         --     v_timeframe VARCHAR2(100);
         --     v_rec VARCHAR2(5);
              v_record VARCHAR2(5);
              v_open VARCHAR2(100);
              v_closed VARCHAR2(100);
              v_PEND VARCHAR2(100);
              v_refSIG VARCHAR2(100);
              v_refreg VARCHAR2(100);
              v_refother VARCHAR2(100);
              v_y varchar2(100);
         BEGIN
              --v_inv := UPPER(v('P44_INV')) ;
              v_record := 'R%';
              v_wildcard := '%';
              v_open := 'OPEN';
              v_closed := 'CLOSED';
              v_PEND := 'PEND';
              v_refSIG := 'REF - SIG';
              v_refreg := 'REF - CLASS';
              v_refother := 'REF - OTHER';
              v_y := 'Y';
              v_sql := 'SELECT REP.INV as INV, REP.cNUMBER as cNUMBER, REP.OPENDATE as OPENDATE,
              REP.ESTCOMPLETE as TARGETDATE, REP.COMPLETED as DATECLOSED, REP.STATUS as STATUS,
              REP.cCODE as cCODE, apex_item.checkbox(1,REP.line,null,'''||v_y||''') line , apex_item.checkbox(1,REP.SIG,null,'''||v_y||''') SIGc ,
              REP.CLASS as CLASS, REP.SUMM as SUMM, REP.AREA as AREA from REP where 1=1';
              IF p_rec is not null then
                   IF p_rec = 'E' then
                        v_sql := v_sql|| ' and upper(REP.cnumber) not like '''||v_record||'''';
                   ELSIF p_rec = 'D' then
                        v_sql := v_sql|| ' and upper(REP.cnumber) like '''||v_record||'''';
                   ELSIF p_rec = 'I' then
                        v_sql := v_sql|| ' and REP.cnumber = REP.cnumber ';
                   end if ;
              end if ;
              IF upper(p_status) not like '%NULL%' then
                   IF upper(p_status) like '%OPEN%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_open||'''';
                   ELSIF upper(p_status) like '%CLOSED%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_closed||'''';
                   ELSIF upper(v_PEND) like '%PEND%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_PEND||'''';
                   ELSIF upper(v_refSIG) like '%REF - SIG%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refSIG||'''';
                   ELSIF upper(v_refreg) like '%REF - CLASS%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refreg||'''';
                   ELSIF upper(v_refother) like '%REF - OTHER%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refother||'''';
                   END IF ;
              END IF ;
              IF p_inv = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.INV),'''||p_inv||''') > 0';
              END IF ;
              IF p_reg = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.CLASS),'''||p_reg||''') > 0';
              END IF ;
              IF p_proarea = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.AREA),'''||p_proarea||''') > 0';
              END IF ;
              IF p_disp = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.disposition),'''||p_disp||''') > 0';
              END IF ;
              IF p_coding = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.ccode),'''||p_coding||''') > 0';
              END IF ;
              IF p_SIG = ' ' THEN
                   v_sql := v_sql||' AND instr(upper(REP.SIG),'''||p_SIG||''') > 0';
              END IF ;
              IF p_word is not null then
                   v_sql := v_sql|| ' and
                   instr(upper(REP.SUMM),
                   upper(nvl('''||p_WORD_IN_SUMM||''',REP.SUMM))) > 0';
              end if ;
              If p_timeframe is not null then
                   if upper(p_timeframe) = 'OPEN' then
                   v_sql := v_sql|| ' and to_date(REP.opendate) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   elsif upper(p_timeframe) = 'CLOSED' then
                   v_sql := v_sql|| ' and to_date(REP.completed) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   elsif upper(p_timeframe) = 'EST' then
                   v_sql := v_sql|| ' and to_date(REP.estcomplete) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   end if;
              end if;
              v_sql := v_sql ||' order by REP.INV ';
              return v_sql;
         end get_query_f;
         function test_pf
              (p_inv VARCHAR2 := UPPER(v('P44_INV'))
              ,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
              ,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
              ,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
              ,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
              ,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
              ,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
              ,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
              ,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
              ,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
              ,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
              ,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
              RETURN test_tab PIPELINED
         is
              type test_c is ref cursor;
              v_row test_tab;
              v_sql varchar2(4000);
              v_cursor test_c;
         begin
              v_sql := get_query_f
                   (p_inv
                   ,p_reg
                   ,p_proarea
                   ,p_disp
                   ,p_coding
                   ,p_status
                   ,p_SIG
                   ,p_inc_sum
                   ,p_word
                   ,p_timeframe
                   ,p_rec
                   ,p_WORD_IN_SUMM
                   ,p_ON_AFTER
                   ,p_ON_BEFORE
              open v_cursor for v_sql;
              fetch v_cursor bulk collect into v_row;
              close v_cursor;
              for i in 1 .. v_row.count loop
                   pipe row (v_row(i));
              end loop;
              return;
         end test_pf;
    end MK_TEST_PF;
    /Regards
    Michael

  • Command the execute sql query and does not clean up data in Table

    Hi Team
    I have an SP, which writes source and target data to Temp Tables and runs except query to get mismatch details
    I am using Exec command to execute source query that writes data to Temp Table, once I execute query using Exec, data is written and immediately #temp table is cleaned, now I cannot use #temp table for comparition.
    Is there any way to execute sql query in SP without using EXEC and will hold the data in temp table.

    You need to create temp table before EXEC statement and rewrite your dynamic query also as below
    declare @source_Sql nvarchar(1000)
    ,@target_Sql nvarchar(1000)
    create table #TempTable1 (name nvarchar(10))
    create table #TempTable2 (name nvarchar(10))
    set @source_Sql = 'INSERT INTO #TempTable1 SELECT [Name] from Employee'
    set @target_Sql = 'INSERT INTO #TempTable2 SELECT [Name] from Employee2'
    EXEC (@source_Sql)   
    EXEC (@target_Sql)             
    select * from #TempTable1 
     Except 
    select * from #TempTable2

  • Materialized Views with Query Rewrite is not getting re-written

    I have tried everything that has been mentioned in all the forums here and on metalink to fix this issue, has any smart APEX user found a solution?
    The issue is the MV with Query rewrite capability is not being re-written.
    Things I have tried
    1) give all Query Rewrite privileges to all 3 APEx schemas and parsing schema;
    2) check trace files with tkprof;
    3) dynamically printed explain plan from v$_SQL on the page while executing the query;
    4) to test in a different environment i created an another DAD using the pl/sql webtool kit and tried the same thing and rewrite works like a charm...
    whats the issue here...why are apex schemas not re-writing the queries????
    appreciate any help...thanks

    Jes, per your request
    --create materialized view
    CREATE MATERIALIZED VIEW "RPLANSWEB"."MV_FCG_ALL_SUMMARY_TAB"
    ORGANIZATION HEAP PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
    STORAGE(INITIAL 81920 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "RPLANSWEB"
    BUILD IMMEDIATE
    USING INDEX
    REFRESH FORCE ON DEMAND
    USING DEFAULT LOCAL ROLLBACK SEGMENT
    ENABLE QUERY REWRITE
    AS SELECT fcg, year, fcg_desc,
    fac, efr, fac_desc, efr_desc,
    ums_round, fcg_allow_drillable allow_drillable,
    MAX(category_code_um1) category_code_um1,
    SUM(perm_asset) perm_asset,
    SUM(temp_asset) temp_asset,
    SUM(semi_asset) semi_asset,
    SUM(lease_asset) lease_asset,
    SUM(planned_constr) planned_constr,
    SUM(all_perm_asset) all_perm_asset,
    SUM(total_asset) total_asset,
    SUM(allow) allow, SUM(rqmt) rqmt,
    SUM(perm_planned_constr) perm_planned_constr,
    SUM(perm_planned_constr_rqmt_delta) perm_planned_constr_rqmt_delta,
    ROUND(DECODE(SUM(rqmt), 0, 0, SUM(all_perm_asset)/SUM(rqmt)*100)) perm_rqmt_pctsat,
    ROUND(DECODE(SUM(allow), 0, 0, SUM(all_perm_asset)/SUM(allow)*100)) perm_allw_pctsat,
    ROUND(DECODE(SUM(rqmt), 0, 0, SUM(total_asset)/SUM(rqmt)*100)) total_rqmt_pctsat,
    ROUND(DECODE(SUM(allow), 0, 0, SUM(total_asset)/SUM(allow)*100)) total_allw_pctsat,
    ROUND(DECODE(SUM(all_perm_asset), 0, 0, SUM(rqmt)/SUM(all_perm_asset)*100)) perm_rqmt_pctutl,
    ROUND(DECODE(SUM(all_perm_asset), 0, 0, SUM(allow)/SUM(all_perm_asset)*100)) perm_allw_pctutl,
    ROUND(DECODE(SUM(total_asset), 0, 0, SUM(rqmt)/SUM(total_asset)*100)) total_rqmt_pctutl,
    ROUND(DECODE(SUM(total_asset), 0, 0, SUM(allow)/SUM(total_asset)*100)) total_allw_pctutl,
    SUM(coarse_screen_asset) coarse_screen_asset,
    SUM(total_excess) total_excess,
    SUM(total_deficit) total_deficit,
    SUM(perm_excess) perm_excess,
    SUM(perm_deficit) perm_deficit,
    SUM(all_perm_excess) all_perm_excess,
    SUM(all_perm_deficit) all_perm_deficit,
    SUM(temp_excess) temp_excess,
    SUM(satisfy_rqmt) satisfy_rqmt
    FROM summary_tab_dd
    GROUP BY fcg, year, fcg_desc,
    fac, efr, fac_desc, efr_desc,
    ums_round, fcg_allow_drillable;
    sql plus> log in as parsing schema user (not APEX_PUBLIC_USER)
    sql plus> SELECT fcg, year, fcg_desc,
    SUM(perm_asset) perm_asset,
    SUM(perm_excess) perm_excess,
    SUM(perm_deficit) perm_deficit,
    SUM(all_perm_excess) all_perm_excess,
    SUM(all_perm_deficit) all_perm_deficit,
    SUM(temp_excess) temp_excess,
    SUM(satisfy_rqmt) satisfy_rqmt
    FROM summary_tab_dd
    where year=2007
    GROUP BY fcg, year, fcg_desc;
    --execution plan
    SELECT STATEMENT     ALL_ROWS     12     291     17460                         
    HASH(GROUP BY)          12     291     17460                         
    MAT_VIEW REWRITE ACCESS(FULL) RPLANSWEB.MV_FCG_ALL_SUMMARY_TAB     ANALYZED     11     291     17460                         "MV_FCG_ALL_SUMMARY_TAB"."YEAR"=2007
    --execution plan from sql workshop (application express)
    SELECT STATEMENT 42,341 55 3,882 1,990,027
    HASH GROUP BY 42,341 55 3,882 1,990,027
    TABLE ACCESS FULL SUMMARY_TAB_DD 109,158 47 3,329 5,130,426 "YEAR" = 2007
    --execution plan from an APEX page (displayed from v$sql and V$SQL_PLAN)
    OPERATION: SELECT STATEMENT OPTIONS: OBJECT_NAME: OBJECT_ALIAS: OBJECT_TYPE: OPTIMIZER: ALL_ROWS SEARCH_COLUMNS: 0 COST: 4600 CARDINALITY: BYTES: CPU_COST: IO_COST: ACCESS_PREDICATES: FILTER_PREDICATES: PROJECTION:
    OPERATION: HASH OPTIONS: GROUP BY OBJECT_NAME: OBJECT_ALIAS: OBJECT_TYPE: OPTIMIZER: SEARCH_COLUMNS: 0 COST: 4600 CARDINALITY: 109158 BYTES: 8732640 CPU_COST: 549150132 IO_COST: 4569 ACCESS_PREDICATES: FILTER_PREDICATES: PROJECTION: "FCG"[VARCHAR2,6], "FCG_DESC"[VARCHAR2,15], SUM("PERM_DEFICIT")[22], SUM("PERM_EXCESS")[22], SUM("SATISFY_RQMT")[22], SUM("TEMP_EXCESS")[22], SUM("ALL_PERM_EXCESS")[22], SUM("ALL_PERM_DEFICIT")[22], SUM("PERM_ASSET")[22]
    OPERATION: TABLE ACCESS OPTIONS: FULL OBJECT_NAME: SUMMARY_TAB_DD OBJECT_ALIAS: SUMMARY_TAB_DD@SEL$1 OBJECT_TYPE: TABLE OPTIMIZER: SEARCH_COLUMNS: 0 COST: 3329
    as you can see while executing the script in sql developer the optimizer is finding the relevant materialized view, not in the case of APEX's SQL Workshop or Page.
    appreciate your time

  • Help with query rewrite and materialized views

    Hello everybody,
    I'm currently learning how to use Oracle (10G Enterprise) and in particular, Materialized Views.
    I seem to have a problem making the optimizer use a materialized view. I have already set the OPTIMIZER_MODE, QUERY_REWRITE_ENABLED and QUERY_REWRITE_INTEGRITY as needed.
    I need to create a materialized view for the following query:
    Q1:
    SELECT PS_SUPPKEY, PS_PARTKEY, PS_SUPPCOST
    FROM PARTSUPPLIER E, PART WHERE PS_PARTKEY=P_PARTKEY and (lower(P_COMMENT) LIKE ''_o_a\%'' or lower(P_COMMENT) LIKE ''_o_u\%'')
    and PS_SUPPCOST =
    (SELECT min( PS_SUPPCOST)
    FROM PARTSUPPLIER I
    WHERE E.PS_PARTKEY=I.PS_PARTKEY)'
    I created it using the following code:
    CREATE MATERIALIZED VIEW mv_q1
    ENABLE QUERY REWRITE
    AS SELECT PS_SUPPKEY, PS_PARTKEY, PS_SUPPCOST
    FROM PARTSUPPLIER E JOIN PART ON (PS_PARTKEY=P_PARTKEY)
    WHERE lower(P_COMMENT) LIKE '_o_a%' or lower(P_COMMENT) LIKE '_o_u%'
    and PS_SUPPCOST=
    (SELECT min( PS_SUPPCOST)
    FROM PARTSUPPLIER I
    WHERE E.PS_PARTKEY=I.PS_PARTKEY);
    I have created the statistics using:
    execute dbms_stats.gather_table_stats('frandres',' mv_q1');
    execute dbms_stats.gather_table_stats('frandres','PARTSUPPLIER');
    execute dbms_stats.gather_table_stats('frandres','PART');
    Both partsupplier and part are tables and not views.
    When executing Q1, the plan does not use the materialized view. Furthermore, when using explain rewrite:
    DECLARE
    qrytxt VARCHAR2(3000) := 'SELECT PS_SUPPKEY, PS_PARTKEY, PS_SUPPCOST
    FROM PARTSUPPLIER E, PART WHERE PS_PARTKEY=P_PARTKEY and (lower(P_COMMENT) LIKE ''_o_a\%'' or lower(P_COMMENT) LIKE ''_o_u\%'')
    and PS_SUPPCOST =
    (SELECT min( PS_SUPPCOST)
    FROM PARTSUPPLIER I
    WHERE E.PS_PARTKEY=I.PS_PARTKEY)';
    BEGIN
    dbms_mview.EXPLAIN_REWRITE
    (qrytxt,'MV_Q1','MV_Q1');
    END;
    I get the following message:
    MESSAGE
    QSM-01150: query did not rewrite
    QSM-01263: query rewrite not possible when query references a dictionary table o
    r view
    QSM-01219: no suitable materialized view found to rewrite this query
    What I can't understand is why it says I am referencing the dictionary or a view?
    If I remove the (lower(P_COMMENT) LIKE ''_o_a\%'' or lower(P_COMMENT) LIKE ''_o_u\%'') condition to the query (using the same materialized view), I get the following message from EXPLAIN_REWRITE:
    MESSAGE
    QSM-01150: query did not rewrite
    QSM-01219: no suitable materialized view found to rewrite this query
    Which is reasonable.
    I don't know if the like condition is messing up my materialized view. Can anyone please help?
    Thanks a lot in advance.
    Edited by: user12072111 on Oct 29, 2009 9:43 PM

    Bingo!
    The 10.2.0.3 patch set is supposed to fix this ( [List of bugs fixed (MVs)|http://www.dbatools.net/doc/bug10203.html#MVIEW] )
    In particular:
    5052568      Query rewrite does not work for SQL with LIKE clause.
    Thank you very much for your message!
    The downside is that I'm only using Oracle for educational purposes and consequently have no Metalink id, so I can't install the patch. Thanks a lot though!

  • Query rewrites with Nested materialized views with different aggregations

    Platform used : Oracle 11g.
    Here is a simple fact table (with measures m1,m2) and dimensions (a) Location (b) Calendar and (c) Product. The business problem is that aggregation operator for measure m1,m2 are different along location dimension and Calendar dimension. The intention is to preaggregate the measures for a product along the calendar dimension and Location dimension and store it as materialized views.
    The direct option is to define a materialized view with Inline queries (Because of the different aggrergation operator, it is not possible to write a query without Inline query). http://download-uk.oracle.com/docs/cd/B28359_01/server.111/b28313/qradv.htm#BABEAJBF documents the limitations that it works only for 'Text match' and 'Equivalent queries' and that is too limiting.
    So decided to have nested materialized view, with first view having just joins(my_dim_mvw_joins), the second view having aggregations along Calendar dimension (my_dim_mvw_calendar) and third view having aggregations along the Location dimension(my_dim_mvw_location). Obviously I do not want the query I fire to know about materialized views and I fire it against the fact table. I see that for the fired query (Which needs aggregations along both Calendar and Location), is rewritten with just second materialized view but not the third. (Had set QUERY_REWRITE_INTEGRITY as TRUSTED) .
    Wanted to know whether there are limitations on Query Writes with nested materialized views? Thanks
    (Have given a simple testable example below. Pls ignore the values given in 'CALENDAR_IDs', 'PRODUCT_IDs' etc as they are the same for all the queries)
    -- Calendar hierarchy table
    CREATE TABLE CALENDAR_HIERARCHY_TREE
    (     "CALENDAR_ID" NUMBER(5,0) NOT NULL ENABLE,
    "HIERARCHY1_ID" NUMBER(5,0),
    "HIERARCHY2_ID" NUMBER(5,0),
    "HIERARCHY3_ID" NUMBER(5,0),
    "HIERARCHY4_ID" NUMBER(5,0),
    CONSTRAINT "CALENDAR_HIERARCHY_TREE_PK" PRIMARY KEY ("CALENDAR_ID")
    -- Location hierarchy table
    CREATE TABLE LOCATION_HIERARCHY_TREE
    (     "LOCATION_ID" NUMBER(3,0) NOT NULL ENABLE,
    "HIERARCHY1_ID" NUMBER(3,0),
    "HIERARCHY2_ID" NUMBER(3,0),
    "HIERARCHY3_ID" NUMBER(3,0),
    "HIERARCHY4_ID" NUMBER(3,0),
    CONSTRAINT "LOCATION_HIERARCHY_TREE_PK" PRIMARY KEY ("LOCATION_ID")
    -- Product hierarchy table
    CREATE TABLE PRODUCT_HIERARCHY_TREE
    (     "PRODUCT_ID" NUMBER(3,0) NOT NULL ENABLE,
         "HIERARCHY1_ID" NUMBER(3,0),
         "HIERARCHY2_ID" NUMBER(3,0),
         "HIERARCHY3_ID" NUMBER(3,0),
         "HIERARCHY4_ID" NUMBER(3,0),
         "HIERARCHY5_ID" NUMBER(3,0),
         "HIERARCHY6_ID" NUMBER(3,0),
         CONSTRAINT "PRODUCT_HIERARCHY_TREE_PK" PRIMARY KEY ("PRODUCT_ID")
    -- Fact table
    CREATE TABLE RETAILER_SALES_TBL
    (     "PRODUCT_ID" NUMBER,
    "PRODUCT_KEY" VARCHAR2(50 BYTE),
    "PLAN_ID" NUMBER,
    "PLAN_PERIOD_ID" NUMBER,
    "PERIOD_ID" NUMBER(5,0),
    "M1" NUMBER,
    "M2" NUMBER,
    "M3" NUMBER,
    "M4" NUMBER,
    "M5" NUMBER,
    "M6" NUMBER,
    "M7" NUMBER,
    "M8" NUMBER,
    "LOCATION_ID" NUMBER(3,0),
    "M9" NUMBER,
    CONSTRAINT "RETAILER_SALES_TBL_LOCATI_FK1" FOREIGN KEY ("LOCATION_ID")
    REFERENCES LOCATION_HIERARCHY_TREE ("LOCATION_ID") ENABLE,
    CONSTRAINT "RETAILER_SALES_TBL_PRODUC_FK1" FOREIGN KEY ("PRODUCT_ID")
    REFERENCES PRODUCT_HIERARCHY_TREE ("PRODUCT_ID") ENABLE,
    CONSTRAINT "RETAILER_SALES_TBL_CALEND_FK1" FOREIGN KEY ("PERIOD_ID")
    REFERENCES CALENDAR_HIERARCHY_TREE ("CALENDAR_ID") ENABLE
    -- Location dimension definition to promote query rewrite
    create DIMENSION LOCATION_DIM
    LEVEL CHAIN IS LOCATION_HIERARCHY_TREE.HIERARCHY1_ID
    LEVEL CONSUMER_SEGMENT IS LOCATION_HIERARCHY_TREE.HIERARCHY3_ID
    LEVEL STORE IS LOCATION_HIERARCHY_TREE.LOCATION_ID
    LEVEL TRADING_AREA IS LOCATION_HIERARCHY_TREE.HIERARCHY2_ID
    HIERARCHY PROD_ROLLUP (
    STORE CHILD OF
    CONSUMER_SEGMENT CHILD OF
    TRADING_AREA CHILD OF
    CHAIN
    -- Calendar dimension definition
    create DIMENSION CALENDAR_DIM
    LEVEL MONTH IS CALENDAR_HIERARCHY_TREE.HIERARCHY3_ID
    LEVEL QUARTER IS CALENDAR_HIERARCHY_TREE.HIERARCHY2_ID
    LEVEL WEEK IS CALENDAR_HIERARCHY_TREE.CALENDAR_ID
    LEVEL YEAR IS CALENDAR_HIERARCHY_TREE.HIERARCHY1_ID
    HIERARCHY CALENDAR_ROLLUP (
    WEEK CHILD OF
    MONTH CHILD OF
    QUARTER CHILD OF
    YEAR
    -- Materialized view with just joins needed for other views
    CREATE MATERIALIZED VIEW my_dim_mvw_joins build immediate refresh complete enable query rewrite as
    select product_id, lht.HIERARCHY1_ID, lht.HIERARCHY2_ID, lht.HIERARCHY3_ID, lht.location_id, cht.HIERARCHY1_ID year,
    cht.HIERARCHY2_ID quarter, cht.HIERARCHY3_ID month, cht.calendar_id week, m1, m3, m7, m9
    from retailer_sales_tbl RS, calendar_hierarchy_tree cht, location_hierarchy_tree lht
    WHERE RS.period_id = cht.CALENDAR_ID
    and RS.location_id = lht.location_id
    and cht.CALENDAR_ID in (10,236,237,238,239,608,609,610,611,612,613,614,615,616,617,618,619,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477)
    AND product_id IN (5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20)
    AND lht.location_id IN (2, 3, 11, 12, 13, 14, 15, 4, 16, 17, 18, 19, 20)
    -- Materialized view which aggregate along calendar dimension
    CREATE MATERIALIZED VIEW my_dim_mvw_calendar build immediate refresh complete enable query rewrite as
    select product_id, HIERARCHY1_ID , HIERARCHY2_ID , HIERARCHY3_ID ,location_id, year, quarter, month, week,
    sum(m1) m1_total, sum(m3) m3_total, sum(m7) m7_total, sum(m9) m9_total,
    GROUPING_ID(product_id, location_id, year, quarter, month, week) dim_mvw_gid
    from my_dim_mvw_joins
    GROUP BY product_id, HIERARCHY1_ID , HIERARCHY2_ID , HIERARCHY3_ID , location_id,
    rollup (year, quarter, month, week);
    -- Materialized view which aggregate along Location dimension
    CREATE MATERIALIZED VIEW my_dim_mvw_location build immediate refresh complete enable query rewrite as
    select product_id, year, quarter, month, week, HIERARCHY1_ID, HIERARCHY2_ID, HIERARCHY3_ID, location_id,
    sum(m1_total) m1_total_1, sum(m3_total) m3_total_1, sum(m7_total) m7_total_1, sum(m9_total) m9_total_1,
    GROUPING_ID(product_id, HIERARCHY1_ID, HIERARCHY2_ID, HIERARCHY3_ID, location_id, year, quarter, month, week) dim_mvw_gid
    from my_dim_mvw_calendar
    GROUP BY product_id, year, quarter, month, week,
    rollup (HIERARCHY1_ID, HIERARCHY2_ID, HIERARCHY3_ID, location_id)
    -- SQL Query Fired (for simplicity have used SUM as aggregation operator for both, but they will be different)
    select product_id, year, HIERARCHY1_ID, HIERARCHY2_ID,
    sum(m1_total) m1_total_1, sum(m3_total) m3_total_1, sum(m7_total) m7_total_1, sum(m9_total) m9_total_1
    from
    select product_id, HIERARCHY1_ID , HIERARCHY2_ID , year,
    sum(m1) m1_total, sum(m3) m3_total, sum(m7) m7_total, sum(m9) m9_total
    from
    select product_id, lht.HIERARCHY1_ID , lht.HIERARCHY2_ID , lht.HIERARCHY3_ID ,lht.location_id, cht.HIERARCHY1_ID year, cht.HIERARCHY2_ID quarter, cht.HIERARCHY3_ID month, cht.calendar_id week,m1,m3,m7,m9
    from
    retailer_sales_tbl RS, calendar_hierarchy_tree cht, location_hierarchy_tree lht
    WHERE RS.period_id = cht.CALENDAR_ID
    and RS.location_id = lht.location_id
    and cht.CALENDAR_ID in (10,236,237,238,239,608,609,610,611,612,613,614,615,616,617,618,619,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477)
    AND product_id IN (5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20)
    AND lht.location_id IN (2, 3, 11, 12, 13, 14, 15, 4, 16, 17, 18, 19, 20)
    GROUP BY product_id, HIERARCHY1_ID , HIERARCHY2_ID , HIERARCHY3_ID , location_id, year
    ) sales_time
    GROUP BY product_id, year,HIERARCHY1_ID, HIERARCHY2_ID
    This Query rewrites only with my_dim_mvw_calendar. (as saw in Query Plan and EXPLAIN_MVIEW). But we would like it to use my_dim_mvw_location as that has aggregations for both dimensions.

    blackhole001 wrote:
    Hi all,
    I'm trying to make my programmer's life easier by creating a database view for them to query the data, so they don't have to worry about joining tables. This sounds like a pretty horrible idea. I say this because you will eventually end up with programmers that know nothing about your data model and how to properly interact with it.
    Additionally, what you will get is a developer that takes one of your views and see's that of the 20 columns in it, it has 4 that he needs. If all those 4 columns comes from a simple 2 table join, but the view has 8 tables, you're wasting a tonne of resources by using the view (and heaven forbid they have to join that view to another view to get 4 of the 20 columns from that other view as well).
    Ideally you'd write stored routines that satisfy exactly what is required (if you are the database resource and these other programmers are java, .net, etc... based) and the front end developers would call those routines customized for an exact purpose.
    Creating views is not bad, but it's by no means a proper solution to having developers not learn or understand SQL and/or the data model.

  • Query rewrite does not happen

    Hello all,
    let me start by wishing you all the best for the forthcoming year !
    And now, the problem
    I am trying to create a materialized view so that a few slow reports that run on OBIEE (10g) make use of query rewrite functionality. Unfortunately any attempt that had made was unsuccessful. I though of posting the query that is created by OBIEE and the different materialized views that i have created, so that anyone that had a similar problem before might help me through it.  So here it goes ( there is a separate discussion for the other query here ) :
    First comes the query that was created by OBIEE when no materialized view existed.
      SELECT DISTINCT D1.c5 AS c1,                  D1.c10 AS c2,                       D1.c9 AS c3,                  D1.c6 AS c4,                  D1.c8 AS c5,                  D1.c8 / NULLIF (D1.c6, 0) AS c6,
                      D1.c7 AS c7,                  D1.c7 / NULLIF (D1.c6, 0) AS c8,        D1.c4 AS c9,                  D1.c3 / NULLIF (D1.c1, 0) AS c10,                     D1.c2 / NULLIF (D1.c1, 0) AS c11
        FROM (SELECT SUM (D1.c6) OVER (PARTITION BY D1.c5) AS c1,
                     SUM (D1.c7) OVER (PARTITION BY D1.c5) AS c2,
                     SUM (D1.c8) OVER (PARTITION BY D1.c5) AS c3,
                     SUM (D1.c4) OVER (PARTITION BY D1.c5) AS c4,
                     D1.c5 AS c5,                 D1.c6 AS c6,                 D1.c7 AS c7,                 D1.c8 AS c8,                 D1.c9 AS c9,                 D1.c10 AS c10
                FROM (  SELECT COUNT (CASE D1.c12 WHEN 1 THEN D1.c11 ELSE NULL END)    AS c4,                    D1.c5 AS c5,                           SUM (D1.c13) AS c6,            
                             SUM (D1.c14) AS c7,                           SUM (D1.c15) AS c8,               COUNT (DISTINCT D1.c11) AS c9,                           D1.c10 AS c10
                          FROM (SELECT                   /*+ PARALLEL(T16913,8) */
                                      T19403.YEAR_MONTH   AS c5,
                                       T7252.PERCENTAGE AS c10,
                                       T366.BARCODE AS c11,
                                       ROW_NUMBER ()   OVER (  PARTITION BY T19403.YEAR_MONTH,   T366.BARCODE  ORDER BY  T19403.YEAR_MONTH DESC,   T366.BARCODE DESC)  AS c12,
                                       T16913.PHA_QUANTITY AS c13,
                                       T16913.EXEC_COST AS c14,
                                       T16913.EXEC_VALUE AS c15
                                  FROM EXECALENDAR_DIM T19403,
                                           DRUG_DIM T366,
                                           PERCENTAGE_DIM T7252,
                                           PRESCDRUG_FACT T16913
                                 WHERE (T366.DWHKEY = T16913.DRU_DWHKEY
                                        AND T7252.DWHKEY = T16913.PER_DWHKEY
                                        AND T16913.EXECUTION_DATE =
                                               T19403.CALENDAR_DATE
                                        AND T19403.YEAR_MONTH = '201212')) D1
                      GROUP BY D1.c5, D1.c10) D1) D1
    ORDER BY c1, c2
    so my first try was that
    CREATE MATERIALIZED VIEW PRESCDRUG_FACT_MV  BUILD IMMEDIATE  REFRESH ON DEMAND  ENABLE QUERY REWRITE  AS
    SELECT  /*+ PARALLEL(PRESCDRUG_FACT,8) */
                     EXECALENDAR_DIM.YEAR_MONTH       as  YEAR_MONTH
                    ,PRESCDRUG_FACT.PER_DWHKEY
                     ,count(*)                            as COUNT_ALL
                     ,COUNT (EXECALENDAR_DIM.YEAR_MONTH)  AS c_YEAR_MONTH
                     ,COUNT (DISTINCT PRESCDRUG_FACT.DRUG_CD) DRUG_CODE
                     ,COUNT (DISTINCT PRESCDRUG_FACT.DRUG_BARCODE) BARCODE
                      -- quantities
                     ,SUM (PRESCDRUG_FACT.PHA_QUANTITY) AS PHA_QUANTITY
                     ,SUM (PRESCDRUG_FACT.DOC_QUANTITY) AS DOC_QUANTITY
                     ,SUM (PRESCDRUG_FACT.APR_QUANTITY) AS APR_QUANTITY
                     -- values
                     ,SUM (PRESCDRUG_FACT.EXEC_VALUE)       AS EXEC_VALUE
                     ,SUM (PRESCDRUG_FACT.PUB_VALUE)        AS PUB_VALUE                
                     ,SUM (PRESCDRUG_FACT.APR_VALUE) AS APR_VALUE                
                     -- costs
                     ,SUM (PRESCDRUG_FACT.EXEC_COST) AS EXEC_COST
                     ,SUM (PRESCDRUG_FACT.PUB_COST) AS PUB_COST
                     ,SUM (PRESCDRUG_FACT.APR_COST) AS APR_COST
       FROM  EXECALENDAR_DIM,    PRESCDRUG_FACT
      WHERE EXECALENDAR_DIM.CALENDAR_DATE   = PRESCDRUG_FACT.EXECUTION_DATE
           AND EXECALENDAR_DIM.YEAR_MONTH in ( '201212')
       GROUP BY   EXECALENDAR_DIM.YEAR_MONTH ,PRESCDRUG_FACT.PER_DWHKEY
    and i got the following messages from DBMS_MVIEW.EXPLAIN_REWRITE
    QSM-01150: query did not rewrite
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, EXECALENDAR_DIM, on column, CALENDAR_DATE
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, EXECUTION_DATE
    QSM-01082: Joining materialized view, PRESCDRUG_FACT_MV, with table, PRESCDRUG_FACT, not possible
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, DRU_DWHKEY
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, EXEC_VALUE
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, EXEC_COST
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, PHA_QUANTITY
    QSM-01155: multi-mv query rewrite not possible when there is a Window Function
    QSM-01219: no suitable materialized view found to rewrite this query
    My second attempt is the following ( in comparison to the first i have added the DRUG_BARCODE column in the grouping clause
    CREATE MATERIALIZED VIEW PRESCDRUG_FACT_MV BUILD IMMEDIATE  REFRESH ON DEMAND ENABLE QUERY REWRITE  AS
    SELECT  /*+ PARALLEL(PRESCDRUG_FACT,8) */
                     EXECALENDAR_DIM.YEAR_MONTH       as  YEAR_MONTH
                     ,PRESCDRUG_FACT.PER_DWHKEY
                  ,PRESCDRUG_FACT.DRUG_BARCODE
                     ,count(*)                                            as COUNT_ALL
                     ,COUNT (EXECALENDAR_DIM.YEAR_MONTH)  AS c_YEAR_MONTH
                     ,COUNT (DISTINCT PRESCDRUG_FACT.DRUG_CD) DRUG_CODE
                     ,COUNT (DISTINCT PRESCDRUG_FACT.DRUG_BARCODE) BARCODE
                     ,COUNT (DISTINCT PRESCDRUG_FACT.PRESC_NUMBER) PRESC_NUMBER
                     ,COUNT (DISTINCT PRESCDRUG_FACT.PRESC_ID)  PRESC_ID
                      -- quantities
                     ,SUM (PRESCDRUG_FACT.PHA_QUANTITY) AS PHA_QUANTITY
                     ,SUM (PRESCDRUG_FACT.DOC_QUANTITY)        AS DOC_QUANTITY
                     ,SUM (PRESCDRUG_FACT.APR_QUANTITY) AS APR_QUANTITY
                     -- values
                     ,SUM (PRESCDRUG_FACT.EXEC_VALUE)       AS EXEC_VALUE
                     ,SUM (PRESCDRUG_FACT.PUB_VALUE)        AS PUB_VALUE                
                     ,SUM (PRESCDRUG_FACT.APR_VALUE) AS APR_VALUE                
                     -- costs
                     ,SUM (PRESCDRUG_FACT.EXEC_COST) AS EXEC_COST
                     ,SUM (PRESCDRUG_FACT.PUB_COST) AS PUB_COST
                     ,SUM (PRESCDRUG_FACT.APR_COST) AS APR_COST
        FROM  EXECALENDAR_DIM,    PRESCDRUG_FACT
      WHERE EXECALENDAR_DIM.CALENDAR_DATE   = PRESCDRUG_FACT.EXECUTION_DATE
           AND EXECALENDAR_DIM.YEAR_MONTH in ( '201212')
       GROUP BY   EXECALENDAR_DIM.YEAR_MONTH ,PRESCDRUG_FACT.PER_DWHKEY,DRUG_BARCODE
    and the results of DBMS_MVIEW.EXPLAIN_REWRITE
    QSM-01150: query did not rewrite
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, EXECALENDAR_DIM, on column, CALENDAR_DATE
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, EXECUTION_DATE
    QSM-01082: Joining materialized view, PRESCDRUG_FACT_MV, with table, PRESCDRUG_FACT, not possible
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, DRU_DWHKEY
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, EXEC_VALUE
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, EXEC_COST
    QSM-01102: materialized view, PRESCDRUG_FACT_MV, requires join back to table, PRESCDRUG_FACT, on column, PHA_QUANTITY
    QSM-01155: multi-mv query rewrite not possible when there is a Window Function
    QSM-01219: no suitable materialized view found to rewrite this query
    third try (rolling up the group results)
    CREATE MATERIALIZED VIEW PRESCDRUG_FACT_MV BUILD IMMEDIATE  REFRESH ON DEMAND ENABLE QUERY REWRITE  AS
    SELECT  /*+ PARALLEL(PRESCDRUG_FACT,8) */
                     EXECALENDAR_DIM.YEAR_MONTH       as  YEAR_MONTH
                     ,PRESCDRUG_FACT.PER_DWHKEY
                  ,PRESCDRUG_FACT.DRUG_BARCODE
                     ,count(*)                                            as COUNT_ALL
                     ,COUNT (EXECALENDAR_DIM.YEAR_MONTH)  AS c_YEAR_MONTH
                     ,COUNT (DISTINCT PRESCDRUG_FACT.DRUG_CD) DRUG_CODE
                     ,COUNT (DISTINCT PRESCDRUG_FACT.DRUG_BARCODE) BARCODE
                     ,COUNT (DISTINCT PRESCDRUG_FACT.PRESC_NUMBER) PRESC_NUMBER
                     ,COUNT (DISTINCT PRESCDRUG_FACT.PRESC_ID)  PRESC_ID
                      -- quantities
                     ,SUM (PRESCDRUG_FACT.PHA_QUANTITY) AS PHA_QUANTITY
                     ,SUM (PRESCDRUG_FACT.DOC_QUANTITY)        AS DOC_QUANTITY
                     ,SUM (PRESCDRUG_FACT.APR_QUANTITY) AS APR_QUANTITY
                     -- values
                     ,SUM (PRESCDRUG_FACT.EXEC_VALUE)       AS EXEC_VALUE
                     ,SUM (PRESCDRUG_FACT.PUB_VALUE)        AS PUB_VALUE                
                     ,SUM (PRESCDRUG_FACT.APR_VALUE) AS APR_VALUE                
                     -- costs
                     ,SUM (PRESCDRUG_FACT.EXEC_COST) AS EXEC_COST
                     ,SUM (PRESCDRUG_FACT.PUB_COST) AS PUB_COST
                     ,SUM (PRESCDRUG_FACT.APR_COST) AS APR_COST
        FROM  EXECALENDAR_DIM,    PRESCDRUG_FACT
      WHERE EXECALENDAR_DIM.CALENDAR_DATE   = PRESCDRUG_FACT.EXECUTION_DATE
           AND EXECALENDAR_DIM.YEAR_MONTH in ( '201212')
       GROUP BY   EXECALENDAR_DIM.YEAR_MONTH     , rollup (PRESCDRUG_FACT.PER_DWHKEY,    DRUG_BARCODE) 
    results from DBMS_MVIEW.EXPLAIN_REWRITE
    QSM-01150: query did not rewrite
    QSM-01295: no suitable grouping_id found in materialized view with grouping sets
    QSM-01155: multi-mv query rewrite not possible when there is a Window Function
    QSM-01219: no suitable materialized view found to rewrite this query  
    So, no luck so far. My guess is that it has to do something with the partition clause that appears in the original query.
    anyway, if anything cross your minds..
    thanks in advance
    Theodore

    Hello again,
    It appeared that, the problem is present only when I try the query in pl/sql developer.
    For some reason, even though I set QUERY_REWRITE_INTEGRITY to STALE_TOLERATED, it behaved as this parameter was set to ENFORCED.
    So the case was that:
    for session - STALE_TOLERATED
    for system - ENFORCED
    In v$parameter2 against "QUERY_REWRITE_INTEGRITY" was shown "stale_tolerated", but the query was not rewritten.
    When I do the same (altering the session and perform the select query) in SQLPlus, everything works as expected - the query is rewritten.
    And I conclude the problem is in PL/SQL Developer (my version is 8.0.1.1498) or something related to this.
    Edited by: Verdi on 2010-2-12 14:00

Maybe you are looking for