Rewrite better a query

I have similar query like below.
Can this query be written to be more fast?
with T as
(select 1 as col1, 10 as col2, 106 as col3 from dual union all
select 5 as col1, 10 as col2, 100 as col3 from dual union all
select 6 as col1, 10 as col2, 104 as col3 from dual union all
select 3 as col1, 10 as col2, 101 as col3 from dual union all
select 4 as col1, 10 as col2, 105 as col3 from dual union all
select 2 as col1, 10 as col2, 103 as col3 from dual)
select * from (select col1 from T where col2=10 order by Col3 desc ) where ROWNUM <= 5;I don't give any execution plans, but i hope someone suggest some solution still.
I know that i can't use function " ROW_NUMBER()" in where-clause, so this won't make any better with the query.
The query should do following things:
1. it should output data ordered as "T.Col3 desc"
2. it should give 5 first rows of the ordered set.

You could use row_number() if you want. But I can't say anything about the performance.
SQL> with T as
  2  (select 1 as col1, 10 as col2, 106 as col3 from dual union all
  3   select 5 as col1, 10 as col2, 100 as col3 from dual union all
  4   select 6 as col1, 10 as col2, 104 as col3 from dual union all
  5   select 3 as col1, 10 as col2, 101 as col3 from dual union all
  6   select 4 as col1, 10 as col2, 105 as col3 from dual union all
  7   select 2 as col1, 10 as col2, 103 as col3 from dual
  8  )
  9  select *
10  from
11     (select col1
12            ,col2
13            ,col3
14            ,row_number() over (order by col3 desc) rn
15      from   t
16      where  col2 = 10
17     )
18  where rn <= 5;
                COL1                 COL2                 COL3                   RN
                   1                   10                  106                    1
                   4                   10                  105                    2
                   6                   10                  104                    3
                   2                   10                  103                    4
                   3                   10                  101                    5

Similar Messages

  • Can I rewrite the following query without using Row_number() function ??!!

    Hello every one, can I rewrite the following query without using the 'ROW_NUMBER() OVER ' part.
    The query is supposed to pull out the records whose CODE is not NULL and has most
    recent date for UPDATE_DATE . The reason I wanted to do this is, When I embed this query
    in between many other queries along with JOINs, My oracle server is unable to execute. So, I thought
    its better to supplant 'ROW_NUMBER() OVER ' logic with something else and try it. .
    SELECT a.* FROM
    (SELECT b.*, ROW_NUMBER() OVER (PARTITION BY b.PIDM
    ORDER BY b.UPDATE_DATE DESC) AS Rno
    FROM
    SELECT *
    FROM SHYNCRO WHERE CODE IS NOT NULL
    )b
    )a
    WHERE a.Rno = 1

    Hi,
    You didn't write over 150 lines of code and then start testing it, did you?
    Don't.
    Take baby steps. Write as little as pssiblem test that. Debug and test again until you have something that does exactly what you want it to do.
    When you have somehting that works perfectly, take one baby step. Add a tiny amount of code, maybe 1 or 2 lines more, and test again.
    When you do get an error, or wrong results, you'll have a much better idea of where the problem is. also, you won't be building code on a flimsy foundation.
    If you need help, post the last working version and the new version with the error. Explain what you're trying to do in the new version.
    The error message indicates line 133. It looks like line 133 of your code is blank. Does your front end allow completely blank lines in the middle of a query? SQL*Plus doesn't by default; you have to say
    SET  SQLBLANKLINES  ONto have a completely blank line in SQL*Plus. (However, lines containing nothing but at commnet are always allowed.)
    You may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (such as indented code) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    The 4 people who posted small code fragments for you to read all did this.  It would be so much easier for people to read your humongeous query if it were formatted.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Kindly help with rewriting the foll. query in a better way

    IS there a better way of writing the foll query:
    When I have 12,50,00,000 rows in Fact Table, the query is unable to execute. I use more than 200GB of temporary space. But I still get Temp Tablespace Full Error:
    --Foll WITH Clause is to calculate Sum of Debit-Credit to calculate BLNC acc. to Group By values
    WITH crnt_blnc_set
    AS ( SELECT f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.pstng_crncy_id AS crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id AS txn_id,
    f.acntng_entry_src AS txn_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    SUM (
    DECODE (
    f.pstng_typ,
    'Credit', f.pstng_amnt,
    0))
    - SUM (
    DECODE (
    f.pstng_typ,
    'Debit', f.pstng_amnt,
    0))
    AS blnc
    FROM FactTable f
    GROUP BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.pstng_crncy_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.acntng_entry_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt),
    --Foll WITH Clause calculates Min and Max Date Ids for the Group By conditions as mentioned
    min_mx_dt
    AS ( SELECT /*+parallel(32)*/
    f.hrarchy_dmn_id AS hrarchy_dmn_id,
    f.prduct_dmn_id AS prduct_dmn_id,
    f.crncy_dmn_id AS crncy_dmn_id,
    f.acnt_dmn_id AS acnt_dmn_id,
    f.txn_id AS txn_id,
    f.txn_src AS txn_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    MIN (f.val_dt_dmn_id) AS min_val_dt,
    GREATEST (MAX (f.val_dt_dmn_id), 2689) AS max_val_dt
    FROM crnt_blnc_set f
    GROUP BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ),
    /*Foll WITH Clause has a Cartesian Join on date_dmn to populate missing entries
    This requirement is because if we have a distinct row for
    hrarchy_dmn_id,
    prduct_dmn_id,
    crncy_dmn_id,
    acnt_dmn_id,
    txn_id,
    txn_src,
    acntng_entry_typ Combination and If wehave a missing entry for that in the max date provided then we actually create those missing entries*/
    slctd_rcrds
    AS ( SELECT /*+ ordered use_nl(d) parallel(mx, 4) */
    mx.hrarchy_dmn_id AS hrarchy_dmn_id,
    mx.prduct_dmn_id AS prduct_dmn_id,
    mx.crncy_dmn_id AS crncy_dmn_id,
    mx.acnt_dmn_id AS acnt_dmn_id,
    mx.txn_id AS txn_id,
    mx.txn_src AS txn_src,
    mx.acntng_entry_typ AS acntng_entry_typ,
    d.date_value AS val_dt,
    d.date_dmn_id AS val_dt_dmn_id
    FROM min_mx_dt mx, date_dmn d
    WHERE mx.min_val_dt <= d.date_dmn_id
    AND mx.max_val_dt >= d.date_dmn_id
    --Foll. WITH clause actually has a outer Join with Firt With Clause to populate the values accordingly
    cmbnd_rcrds
    AS (
    SELECT /*+ USE_HASH(c) */ s.hrarchy_dmn_id AS hrarchy_dmn_id,
    s.prduct_dmn_id AS prduct_dmn_id,
    s.crncy_dmn_id AS crncy_dmn_id,
    s.acnt_dmn_id AS acnt_dmn_id,
    s.txn_id AS txn_id,
    s.txn_src AS txn_src,
    s.acntng_entry_typ AS acntng_entry_typ,
    s.val_dt_dmn_id AS val_dt_dmn_id,
    NVL (c.revsn_dt, s.val_dt) AS revsn_dt,
    NVL (c.blnc, 0) AS blnc,
    0 AS prvs_rcrd_ind
    FROM slctd_rcrds s, crnt_blnc_set c
    WHERE s.hrarchy_dmn_id = c.hrarchy_dmn_id(+)
    AND s.prduct_dmn_id = c.prduct_dmn_id(+)
    AND s.crncy_dmn_id = c.crncy_dmn_id(+)
    AND s.acnt_dmn_id = c.acnt_dmn_id(+)
    AND s.txn_id = c.txn_id(+)
    AND s.txn_src = c.txn_src(+)
    AND s.acntng_entry_typ = c.acntng_entry_typ(+)
    AND s.val_dt_dmn_id = c.val_dt_dmn_id(+))
    Select * from cmbnd_rcrds

    Thanks for the response Alfonso. I have tried that as well. But Create Table as Also uses Temp Storage till it's created. And that again gives the same error as well.
    Anyways I am now trying with a smaller set. This much piece gets executed in Half an hour but the next piece where we pivot the data is taking forever now.
    That piece is as follows:
    (SELECT /*+parallel(8)*/
    f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ
    ORDER BY d.date_value)
    AS crnt_blnc,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    d.fin_mnth_num
    || d.fin_year_strt
    || d.fin_year_end
    ORDER BY d.date_value)
    / d.mnth_to_dt
    AS mtd_avg,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    d.fin_year_strt || d.fin_year_end
    ORDER BY d.date_value)
    / yr_to_dt
    AS ytd_avg,
    f.prvs_rcrd_ind AS prvs_rcrd_ind
    FROM cmbnd_rcrds f, thor_date_dmn d
    WHERE d.holidaY_ind = 0 AND f.val_dt_dmn_id = d.date_dmn_id)
    SELECT f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id AS txn_id,
    f.txn_src AS acntng_entry_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    f.crnt_blnc,
    f.mtd_avg,
    f.ytd_avg,
    'EOD TB ETL' AS crtd_by,
    SYSTIMESTAMP AS crtn_dt,
    NULL AS mdfd_by,
    NULL AS mdfctn_dt
    FROM fnl_set f
    WHERE f.prvs_rcrd_ind = 0
    ORDER BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id
    Any other way to pivot this?
    Also I am getting a lot of foll wait events:
    PX Deq Credit :Send blkd
    PX Deq :Table Q Normal
    Direct Path Write Temp
    And Direct Path Read Temp.

  • 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 a sql query

    Hi All
    i want to rewite the sql from
    select x
    from table1 t1
    where y =
    ( select max(y) from table1 t2 where t1.id = t2.id )
    to be more simple
    i believe that analytic functions can do that
    i tried
    select x
    from table1
    having y = max(y) over()
    but it did not work
    any help please
    thanks

    thanks for all of you
    i have rewriten the query , BUT the code did not become smaller , and i don't know which execution plan is better , any suggestions?
    Old SQL:
    SELECT scl1.claim_type,
    scp.publisher_no,
    scp.publisher_percentage,
    sys.dual_claim_publisher_no,
    effective_date
    FROM song_claims scl1, song_claim_publishers scp, system_parameters sys
    WHERE scl1.song_claim_no = scp.song_claim_no
    AND scl1.song_no = 2
    AND scl1.effective_date =
    SELECT MAX(scl2.effective_date)
    FROM song_claims scl2
    WHERE scl2.song_no = 21
    AND (scl2.effective_date <= '01-jan-2000'
    OR scl2.effective_date =
    SELECT MIN(scl3.effective_date)
    FROM song_claims scl3
    WHERE scl3.song_no = 2
    Old SQL Execution Plan:
    SELECT STATEMENT, GOAL = CHOOSE               Cost=8     Cardinality=1     Bytes=30
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIM_PUBLISHERS     Cost=3     Cardinality=1     Bytes=10
    NESTED LOOPS               Cost=8     Cardinality=1     Bytes=30
    NESTED LOOPS               Cost=5     Cardinality=1     Bytes=20
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIMS     Cost=3     Cardinality=1     Bytes=17
    INDEX UNIQUE SCAN     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=2     Cardinality=1     
    SORT AGGREGATE                    Cardinality=1     Bytes=12
    FIRST ROW               Cost=3     Cardinality=1     Bytes=12
    INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
    SORT AGGREGATE                    Cardinality=1     Bytes=12
    FIRST ROW               Cost=3     Cardinality=1     Bytes=12
    INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
    TABLE ACCESS FULL     Object owner=WISSYS     Object name=SYSTEM_PARAMETERS     Cost=2     Cardinality=1     Bytes=3
    INDEX RANGE SCAN     Object owner=CRS     Object name=XPKSONG_CLAIM_PUBLISHERS     Cost=2     Cardinality=1     
    New SQL:
    select * from
    SELECT scl1.claim_type,
    scp.publisher_no,
    scp.publisher_percentage,
    sys.dual_claim_publisher_no,
    scl1.effective_date,
    max (effective_date) over (partition by null) max_eff_date,
    min (effective_date) over (partition by null) min_eff_date
    FROM song_claims scl1, song_claim_publishers scp, system_parameters sys
    WHERE scl1.song_claim_no = scp.song_claim_no
    AND scl1.song_no = 2
    where
    effective_date = case when max_eff_date <= '01-jan-2000' then to_char(max_eff_date)
    when min_eff_date > '01-jan-2000' then to_char(min_eff_date)
    else (SELECT to_char(MAX(effective_date)) FROM song_claims scl2 WHERE scl2.song_no = 2 and scl2.effective_date < '01-jan-2000')
    end
    New SQL Execution Plan:
    SELECT STATEMENT, GOAL = CHOOSE               Cost=10     Cardinality=1     Bytes=69
    VIEW     Object owner=BFH          Cost=10     Cardinality=1     Bytes=69
    WINDOW BUFFER               Cost=10     Cardinality=1     Bytes=30
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIM_PUBLISHERS     Cost=3     Cardinality=1     Bytes=10
    NESTED LOOPS               Cost=8     Cardinality=1     Bytes=30
    MERGE JOIN CARTESIAN               Cost=5     Cardinality=1     Bytes=20
    TABLE ACCESS FULL     Object owner=WISSYS     Object name=SYSTEM_PARAMETERS     Cost=2     Cardinality=1     Bytes=3
    BUFFER SORT               Cost=3     Cardinality=1     Bytes=17
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIMS     Cost=3     Cardinality=1     Bytes=17
    INDEX RANGE SCAN     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=2     Cardinality=1     
    INDEX RANGE SCAN     Object owner=CRS     Object name=XPKSONG_CLAIM_PUBLISHERS     Cost=2     Cardinality=1     
    SORT AGGREGATE                    Cardinality=1     Bytes=12
    FIRST ROW               Cost=3     Cardinality=1     Bytes=12
    INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
    Thanks

  • 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

  • Rewrite the max query...

    The inner select statement works fast and few columns generated based on A.QSN_DESC_X values, AND to get a single row I am doing a group by on cmpltn_i by taking the max row. When I do this group by the query takes approx 5 mnts. The inner query returns 227270 records. The final query give 37,000 records.
    Can someone suggest any better way to write this query?
    select
    CMPLTN_I,
    max(emp_i) as emp_i,
    max(first_name) as first_name,
    max(last_name) as last_name,
    max (vendor) as vendor,
    max (product_type) as product_type,
    max (event_type) as event_type,
    max (dollar_amt) as dollar_amt,
    max (date_received) as date_received,
    max (branch_code) as branch_code
    from (
    select   /*+DRIVING_SITE(A)*/   
    B.CMPLTN_I,
    B.emp_i, 
    E.EMP_1ST_NME_X as first_name,
    E.EMP_LAST_NME_X as last_name, 
    case when substr(A.QSN_DESC_X,1,6) = 'Vendor' then A.CHCE_DESC_X else null end as vendor,
    case when substr(A.QSN_DESC_X,1,12) = 'Product Type' then A.CHCE_DESC_X else null end  as product_type,
    case when substr(A.QSN_DESC_X,1,10) = 'Event Type' then A.CHCE_DESC_X else null end as  event_type,
    case when substr(A.QSN_DESC_X,1,13) = 'Dollar Amount' then A.CHCE_DESC_X else null end as  dollar_amt,
    case when substr(A.QSN_DESC_X,1,13) = 'Date Received' then A.CHCE_DESC_X else null end as date_received,
    case when substr(A.QSN_DESC_X,1,16) = 'Branch Wire Code' then A.CHCE_DESC_X else null end as branch_code        
    from  OAT.FORM_FACT@REMOTE_AB A, OAT.FORM_CMPLTN_FACT@REMOTE_AB B, empl_info_dimn E
    where  A.CMPLTN_I  =  B.CMPLTN_I
    and      B.CMPLTN_C  =  'C'
    and      B.app_i  = '20'
    and      E.emp_i = B.emp_i
    group by
    CMPLTN_I

    10g release 2.
    cost based, statistics are good
    without driving site hint, the response time is bad
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 2770348679
    | Id  | Operation              | Name                       | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | Inst   |IN-OUT|
    |   0 | SELECT STATEMENT REMOTE|                            |   922K|   139M|       |   104K  (1)| 00:20:49 |        |      |
    |   1 |  SORT GROUP BY         |                            |   922K|   139M|   300M|   104K  (1)| 00:20:49 |        |      |
    |*  2 |   HASH JOIN            |                            |   922K|   139M|  4976K| 71818   (2)| 00:14:22 |        |      |
    |   3 |    REMOTE              | EMPL_INFO_DIMN             | 86311 |  3961K|       | 10903   (1)| 00:02:11 |      ! | R->S |
    |*  4 |    HASH JOIN           |                            |   923K|    97M|       | 55274   (2)| 00:11:04 |        |      |
    |*  5 |     TABLE ACCESS FULL  | FORM_RECIPIENT_CMPLTN_FACT | 24223 |   331K|       |   698   (3)| 00:00:09 | OATP0~ |      |
    PLAN_TABLE_OUTPUT
    |   6 |     TABLE ACCESS FULL  | FORM_RESP_FACT             |    10M|  1013M|       | 54439   (2)| 00:10:54 | OATP0~ |      |
    Predicate Information (identified by operation id):
       2 - access("A1"."EMP_I"="A2"."EMP_I")
       4 - access("A3"."CMPLTN_I"="A2"."CMPLTN_I")
       5 - filter("A2"."APP_I"=20 AND "A2"."CMPLTN_I" IS NOT NULL AND "A2"."CMPLTN_C"='C')
    Remote SQL Information (identified by operation id):
    PLAN_TABLE_OUTPUT
       3 - SELECT /*+ USE_HASH ("A1") */ "EMP_I","EMP_LAST_NME_X","EMP_1ST_NME_X" FROM "DWCSADM"."EMPL_INFO_DIMN" "A1"
           (accessing '!' )
    Note
       - fully remote statement
    31 rows selected.

  • 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/

  • Need help in rewriting a sql query

    Can any one please tell me if there is any utility that can help me correcting the sql I have I need to tune the query as its taking lot of time. I want to use some tool that will help me re-formating the query.
    Any help in this regard will be highly appreciated.

    If you think that Oracle SQL Tuning Tools like SQL Tuning Advisor and SQL Access Advisor are not helping.
    You might look into thrid party tools like Quest- SQL Navigator and TOAD.
    But I don't advise this based on the following:
    Re: Oracle Third Party Tools and Oracle Database
    Oracle have enough tools of its own to satisfy the various needs.
    Adith

  • URL-Rewriting or append query string in URL

    Hi
    I have one other quetion related to my project I am working and need to finish tonight.
    I read one table in first JSP and want to send one column, eventname to the other JSP. Can I use URL-rewriting. I need to keep the event name thruoghout too.
    Is this syntax correct..
    Please help me !!!

    Syntax is:
    <a href="ListEvents.jsp?event=eventname">Click me</a>In the JSP, there are two things you may need to do when generating the link.
    1. Encode the URL - this is needed if any arguments (in this case "eventname") might include spaces or special characters.
    2. Apply URL rewriting info if this may be needed. This will add "&JSESSIONID=xxxxx" if required.
    <%
    String link = "ListEvents.jsp?event=" + getEventName();  // or whatever gets the event name
    link = java.util.URLEncode.encode(s,"UTF-8");    // encode the event name data
    link = response.encodeURL(link);                      // add the session id if URL rewriting in use
    %>
    <a href="<%=link%>">Click Me</a>The event name is retrieved using request.getParameter("event")

  • Help rewriting this XMLTable query.

    Hi,
    I rewrote this query:
         SELECT VALUE(k) ts_value,
                s.transactionsetcontrolnumber ts,
                t.xmlintid,
                i.isaid,
                stid,
                g.sendorcode || '!' || g.receivercode || '!' || s.transactionsetid || '!I' geteditpparameter,
                EXTRACTVALUE(VALUE(k), '/TS_850/BEG/BEG03') || '-' ||
                (SELECT N104
                   FROM xmltable('/TS_850/GROUP_5/N1' passing VALUE(k) columns N101
                                 VARCHAR2(2) path 'N101',
                                 N104 VARCHAR2(32) path 'N104')
                  WHERE N101 = 'OB') beg_n104,
                g.sendorcode || '!' || g.receivercode || '!' ||
                (SELECT N103 || '!' || N104
                   FROM xmltable('/TS_850/GROUP_5/N1' passing VALUE(k) columns N101
                                 VARCHAR2(2) path 'N101',
                                 N103 VARCHAR2(32) path 'N103',
                                 N104 VARCHAR2(32) path 'N104')
                  WHERE N101 = 'OB') getedicuststxparameter,
                (SELECT to_date(dtm02, 'YYYYMMDD')
                   FROM xmltable('/TS_850/DTM' passing VALUE(k) columns dtm01
                                 VARCHAR2(3) path 'DTM01',
                                 dtm02 VARCHAR2(32) path 'DTM02')
                  WHERE DTM01 <> '061') requireddate,
                (SELECT SUM(SAC07)
                   FROM xmltable('/TS_850/GROUP_1/SAC' passing VALUE(k) columns
                                 SAC01 VARCHAR2(2) path 'SAC01',
                                 SAC07 VARCHAR2(32) path 'SAC07')
                  WHERE SAC01 = 'A') sumsac07
           FROM edi_xml_int t,
                edi_isa i,
                edi_gs g,
                edi_st s,
                TABLE(XMLSEQUENCE(EXTRACT(x12_850, '/X12/TS_850'))) k
          WHERE s.gsid = g.gsid
            AND g.isaid = i.isaid
            AND t.isaid = i.isaid
            AND s.transactionsetcontrolnumber =
                EXTRACTVALUE(VALUE(k), '/TS_850/ST/ST02')
            AND t.processeddate IS NULL
            AND s.transactionsetid = '850'
            AND TRIM(i.senderid) = '0722717110100'
            and s.updateddate is null order by s.stid;
    Explain Plan for this is:
    | Id  | Operation                          | Name                   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                   |                        |  8077 |    16M|  1056   (2)| 00:00:13 |
    |*  1 |  COLLECTION ITERATOR PICKLER FETCH | XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |*  2 |  COLLECTION ITERATOR PICKLER FETCH | XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |*  3 |  COLLECTION ITERATOR PICKLER FETCH | XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |   4 |  SORT AGGREGATE                    |                        |     1 |     2 |            |       |
    |*  5 |   COLLECTION ITERATOR PICKLER FETCH| XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |   6 |  NESTED LOOPS                      |                        |  8077 |    16M|  1056   (2)| 00:00:13 |
    |   7 |   NESTED LOOPS                     |                        |    45 | 95175 |    55   (0)| 00:00:01 |
    |   8 |    NESTED LOOPS                    |                        |    45 |  3510 |     4   (0)| 00:00:01 |
    |   9 |     MERGE JOIN CARTESIAN           |                        |    45 |  2070 |     3   (0)| 00:00:01 |
    |* 10 |      TABLE ACCESS BY INDEX ROWID   | EDI_ST                 |    45 |  1125 |     2   (0)| 00:00:01 |
    |  11 |       INDEX FULL SCAN              | EDI_ST_PK              |    45 |       |     1   (0)| 00:00:01 |
    |  12 |      BUFFER SORT                   |                        |     1 |    21 |     1   (0)| 00:00:01 |
    |  13 |       TABLE ACCESS BY INDEX ROWID  | EDI_ISA                |     1 |    21 |     1   (0)| 00:00:01 |
    |* 14 |        INDEX RANGE SCAN            | EDI_ISA_IX_1           |     1 |       |     0   (0)| 00:00:01 |
    |* 15 |     TABLE ACCESS BY INDEX ROWID    | EDI_GS                 |     1 |    32 |     1   (0)| 00:00:01 |
    |* 16 |      INDEX UNIQUE SCAN             | EDI_GS_PK              |     1 |       |     0   (0)| 00:00:01 |
    |* 17 |    TABLE ACCESS FULL               | EDI_XML_INT            |     1 |  2037 |     1   (0)| 00:00:01 |
    |* 18 |   COLLECTION ITERATOR PICKLER FETCH| XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    Predicate Information (identified by operation id):
       1 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/N101')),50,1,2) AS
                  VARCHAR2(2) )='OB')
       2 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/N101')),50,1,2) AS
                  VARCHAR2(2) )='OB')
       3 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/DTM01')),50,1,2) AS
                  VARCHAR2(3) )<>'061')
       5 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/SAC01')),50,1,2) AS
                  VARCHAR2(2) )='A')
      10 - filter("S"."TRANSACTIONSETID"='850' AND "S"."UPDATEDDATE" IS NULL)
      14 - access(TRIM("SENDERID")='0722717110100')
      15 - filter("G"."ISAID"="I"."ISAID")
      16 - access("S"."GSID"="G"."GSID")
      17 - filter("T"."PROCESSEDDATE" IS NULL AND "T"."ISAID"="I"."ISAID")
      18 - filter("S"."TRANSACTIONSETCONTROLNUMBER"=EXTRACTVALUE(VALUE(KOKBF$),'/TS_850/ST/ST02'))
    Note
       - dynamic sampling used for this statement
    47 rows selected.I rewrote this to this:
    SELECT k.main ts_value,
                s.transactionsetcontrolnumber ts,
                t.xmlintid,
                i.isaid,
                stid,
                g.sendorcode || '!' || g.receivercode || '!' || s.transactionsetid || '!I' geteditpparameter,
                EXTRACTVALUE(k.main, '/TS_850/BEG/BEG03') || '-' ||
                (SELECT N104
                   FROM xmltable('/TS_850/GROUP_5/N1' passing k.main columns N101
                                 VARCHAR2(2) path 'N101',
                                 N104 VARCHAR2(32) path 'N104')
                  WHERE N101 = 'OB') beg_n104,
                g.sendorcode || '!' || g.receivercode || '!' ||
                (SELECT N103 || '!' || N104
                   FROM xmltable('/TS_850/GROUP_5/N1' passing k.main columns N101
                                 VARCHAR2(2) path 'N101',
                                 N103 VARCHAR2(32) path 'N103',
                                 N104 VARCHAR2(32) path 'N104')
                  WHERE N101 = 'OB') getedicuststxparameter,
                (SELECT to_date(dtm02, 'YYYYMMDD')
                   FROM xmltable('/TS_850/DTM' passing k.main columns dtm01
                                 VARCHAR2(3) path 'DTM01',
                                 dtm02 VARCHAR2(32) path 'DTM02')
                  WHERE DTM01 <> '061') requireddate,
                (SELECT SUM(SAC07)
                   FROM xmltable('/TS_850/GROUP_1/SAC' passing k.main columns
                                 SAC01 VARCHAR2(2) path 'SAC01',
                                 SAC07 VARCHAR2(32) path 'SAC07')
                  WHERE SAC01 = 'A') sumsac07
      FROM edi_xml_int t,
           edi_isa i,
           edi_gs g,
           edi_st s,
           xmltable('/X12/TS_850' passing x12_850 columns main xmltype path
                    '/TS_850',
                    st02 varchar2(32) path '/TS_850/ST/ST02') k
    WHERE s.gsid = g.gsid
       AND g.isaid = i.isaid
       AND t.isaid = i.isaid
       AND s.transactionsetcontrolnumber = k.st02
       AND t.processeddate IS NULL
       AND s.transactionsetid = '850'
       AND TRIM(i.senderid) = '0722717110100'
       and s.updateddate is null
    order by s.stid;
    Explain plan for this is:
    | Id  | Operation                          | Name                   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                   |                        |  8077 |    16M|  1056   (2)| 00:00:13 |
    |*  1 |  COLLECTION ITERATOR PICKLER FETCH | XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |*  2 |  COLLECTION ITERATOR PICKLER FETCH | XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |*  3 |  COLLECTION ITERATOR PICKLER FETCH | XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |   4 |  SORT AGGREGATE                    |                        |     1 |     2 |            |       |
    |*  5 |   COLLECTION ITERATOR PICKLER FETCH| XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    |   6 |  NESTED LOOPS                      |                        |  8077 |    16M|  1056   (2)| 00:00:13 |
    |   7 |   NESTED LOOPS                     |                        |    45 | 95175 |    55   (0)| 00:00:01 |
    |   8 |    NESTED LOOPS                    |                        |    45 |  3510 |     4   (0)| 00:00:01 |
    |   9 |     MERGE JOIN CARTESIAN           |                        |    45 |  2070 |     3   (0)| 00:00:01 |
    |* 10 |      TABLE ACCESS BY INDEX ROWID   | EDI_ST                 |    45 |  1125 |     2   (0)| 00:00:01 |
    |  11 |       INDEX FULL SCAN              | EDI_ST_PK              |    45 |       |     1   (0)| 00:00:01 |
    |  12 |      BUFFER SORT                   |                        |     1 |    21 |     1   (0)| 00:00:01 |
    |  13 |       TABLE ACCESS BY INDEX ROWID  | EDI_ISA                |     1 |    21 |     1   (0)| 00:00:01 |
    |* 14 |        INDEX RANGE SCAN            | EDI_ISA_IX_1           |     1 |       |     0   (0)| 00:00:01 |
    |* 15 |     TABLE ACCESS BY INDEX ROWID    | EDI_GS                 |     1 |    32 |     1   (0)| 00:00:01 |
    |* 16 |      INDEX UNIQUE SCAN             | EDI_GS_PK              |     1 |       |     0   (0)| 00:00:01 |
    |* 17 |    TABLE ACCESS FULL               | EDI_XML_INT            |     1 |  2037 |     1   (0)| 00:00:01 |
    |* 18 |   COLLECTION ITERATOR PICKLER FETCH| XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    Predicate Information (identified by operation id):
       1 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/N101')),50,1,2) AS
                  VARCHAR2(2) )='OB')
       2 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/N101')),50,1,2) AS
                  VARCHAR2(2) )='OB')
       3 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/DTM01')),50,1,2) AS
                  VARCHAR2(3) )<>'061')
       5 - filter(CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALUE(KOKBF$),'/*/SAC01')),50,1,2) AS
                  VARCHAR2(2) )='A')
      10 - filter("S"."TRANSACTIONSETID"='850' AND "S"."UPDATEDDATE" IS NULL)
      14 - access(TRIM("SENDERID")='0722717110100')
      15 - filter("G"."ISAID"="I"."ISAID")
      16 - access("S"."GSID"="G"."GSID")
      17 - filter("T"."PROCESSEDDATE" IS NULL AND "T"."ISAID"="I"."ISAID")
      18 - filter("S"."TRANSACTIONSETCONTROLNUMBER"=CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(SYS_XQEXTRACT(VALU
                  E(KOKBF$),'/TS_850/ST/ST02')),50,1,2) AS varchar2(32) ))
    Note
       - dynamic sampling used for this statement
    48 rows selected.Now, I was wondering if you can have just one implementation of XMLTable in the query which will reduce the complexity of this. Both the queries looked like they gave me the same results.
    Thank you,
    Rahul.

    It's quite hard to tune a query without seeing the table structure and available indices as well as relationship between each other but I'll try.
    In your sql which you've given the table alias AD, you have this filter criteria
                  AND    FIELD_NAME IN (                        
                         SELECT FIELD_NAME
                         FROM   APPLICATION_FIELDS                            
                         WHERE  FIELD_TYPE IN ('Checkbox','Radio','Select','SelectM', 'RadioHoriz','RadioPara')
                         ) </br>
    My question is, is FIELD_NAME a column in the APPLICATION_DATA table? If it is, try moving this clause outside of the current sub-query it is in, i.e. one more level up. It looks like you put them inside the wrong level.
    I would also try converting this <COL> IN <SUB-QUERY> to a join, if that wouldn't affect the no. of rows returned. I can't tell for sure since I dont know the relationship between your tables.
    It looks to me like you're doing this
    SELECT <col list>
    FROM   ( SELECT                                         -- LEVEL 1
             FROM   APPLICATION_DATA AD
             WHERE  AD.APPLICAITON_ID IN (                  -- LEVEL 2
                    SELECT
                    FROM   APPLICATIONS A
                    WHERE  A.JOB_ID IN (
                           <SUBQUERY>
                    AND    A.ACCOUNT_ID IN (
                           <SUBQUERY>
                    AND FIELDNAME IN ( -- SHOULD BE INSIDE LEVEL1
    <SUBQUERY>
           ) AD,
           ( SELECT ....
           ) FD
    WHERE  ....

  • Rewrite the static query to dynamic SQL

    Can any one please help me to write a dynamic query within a pl/sql for the following SQL??
    This is for the set ('25','04'). the number of list could be n .
    The column_type ranges from(1..6) and
    the column_amt1 ranges from(1..6)
    SELECT t.claim_no, t.cert_no, t.rec_code,
    (NVL(decode(t.column_type1,'25',NVL (t.column_amt1, 0)),0)+
        NVL(decode(t.column_type1,'04',NVL(t.column_amt1, 0)),0 )
      +
       (NVL(decode(t.column_type2,'25',NVL (t.column_amt2, 0)),0)+
        NVL(decode(t.column_type2,'04',NVL(t.column_amt2, 0)),0 )
      +
       (NVL(decode(t.column_type3,'25',NVL (t.column_amt3, 0)),0)+
        NVL(decode(t.column_type3,'04',NVL(t.column_amt3, 0)),0 )
      +
       (NVL(decode(t.column_type4,'25',NVL (t.column_amt4, 0)),0)+ 
         NVL(decode(t.column_type4,'04',NVL(t.column_amt4, 0)),0 )
      +
         (NVL(decode(t.column_type5,'25',NVL (t.column_amt5, 0)),0)+ 
          NVL(decode(t.column_type5,'04',NVL(t.column_amt5, 0)),0 )
      +
          (NVL(decode(t.column_type6,'25',NVL (t.column_amt6, 0)),0)+ 
           NVL(decode(t.column_type6,'04',NVL(t.column_amt6, 0)),0 )) amt from test_detail t;
       Thanks in Advance
    Hena

    user11253970 wrote:
    This is the part of a procedure.NowThe query is only for type '25' and '04' .It could be more in numbers in future.So I want to maintain a dynamic sql irrespective of the number of types I use.Then first thing you must do is rename column case since it is PL/SQL reserved word (I renamed it to case_id). Then you could create a couple of SQL types and a pipelined function:
    CREATE OR REPLACE
      TYPE test_detail_copay_obj
        AS
          OBJECT(
                 case_id char(10),
                 item    char(9),
                 code    char(2),
                 copay   number(10,2)
    CREATE OR REPLACE
      TYPE test_detail_copay_tbl
        AS
          TABLE OF test_detail_copay_obj
    CREATE OR REPLACE
      FUNCTION test_detail_copay(p_type_list varchar2)
        RETURN test_detail_copay_tbl
        PIPELINED
        IS
            v_cur sys_refcursor;
            v_copay_obj test_detail_copay_obj;
        BEGIN
            OPEN v_cur FOR 'select  test_detail_copay_obj(case_id,
                                                          item,
                                                          code,
                                                          case
                                                            when type1 in (' || p_type_list || ') then nvl(amt1,0)
                                                            else 0
                                                          end +
                                                          case
                                                            when type2 in (' || p_type_list || ') then nvl(amt2,0)
                                                            else 0
                                                          end +
                                                          case
                                                            when type3 in (' || p_type_list || ') then nvl(amt3,0)
                                                            else 0
                                                          end +
                                                          case
                                                            when type4 in (' || p_type_list || ') then nvl(amt4,0)
                                                            else 0
                                                          end +
                                                          case
                                                            when type5 in (' || p_type_list || ') then nvl(amt5,0)
                                                            else 0
                                                          end +
                                                          case
                                                            when type6 in (' || p_type_list || ') then nvl(amt6,0)
                                                            else 0
                                                          end
                              from  test_detail';
            LOOP
              FETCH  v_cur
                INTO v_copay_obj;
              EXIT WHEN v_cur%notfound;
              PIPE ROW(v_copay_obj);
            END LOOP;
            RETURN;
    END;
    /Now:
    SQL> select  *
      2    from  table(test_detail_copay('''25'',''04'''))
      3  /
    CASE_ID    ITEM      CO      COPAY
    EML3371015 133761570 10        355
    EML3371015 133761570 10         20
    EML3371015 133761570 10          5
    EMC6369600 140328551 10         54
    EMH6353995 140328551 11      26.04
    SQL> select  *
      2    from  table(test_detail_copay('''25'''))
      3  /
    CASE_ID    ITEM      CO      COPAY
    EML3371015 133761570 10        300
    EML3371015 133761570 10         20
    EML3371015 133761570 10          5
    EMC6369600 140328551 10          0
    EMH6353995 140328551 11       5.52
    SQL> SY.

  • How to format better my query for a report?

    I have a shell script to run sql queries to get database information everyday.
    However here below, I want some columns to be indented to the right, and I also want to format the column with %.
    Also for the column name , underneath the column name, there are lines which very long and over one line, how to make it within a linesize?
    Checking DataGuard Status/Information
    message error time
    FACILITY SEVERITY DEST_ID number code CAL stamp MESSAGE
    ======================== ============= ========== ========== ========== === ========= ================================================================================================================================================================================================================================================================
    Thanks,

    Refer the below link for all format models and elements..etc
    http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm
    Hope this helps,
    Regards
    http://www.oracleracexpert.com
    Transportable tablespace export and import
    http://www.oracleracexpert.com/2009/09/transportable-tablespace-export-and.html
    Oracle data pump export/import with examples.
    http://www.oracleracexpert.com/2009/08/oracle-data-pump-exportimport.html

  • Update rewrite for the query below

    UPDATE LAB_ST_SMRY LLS
    SET (ST_CODE, ST_NAME, ST_DESC,IMAGE, ST_ID, ID, DIS_TYPE, ZIP_TYPE,
    ACTE_IND, USER, UPDATE_DATE)
    = (SELECT LLT.ST_CODE, LLT.ST_NAME, LLT.ST_DESC, LLT.IMAGE, LLT.ST_ID, LLT.ID,
    LLT.ASSOC_DISC,1,1, 'LabWork', SYSDATE
    FROM LAB_ST_TEMP LLT
    INNER JOIN LAB_TEMP LT
    ON LLT.ST_CODE=LT.ST_CODE
    WHERE LLT.ST_ID=LLS.ST_ID
    GROUP BY LLT.ST_CODE, LLT.ST_NAME, LLT.ST_DESC, LLT.IMAGE, LLT.ST_ID, LLT.ID,LLT.ASSOC_DISC
    i am getting error that cannot update st_code to null.
    I have 15 records in LAB_ST_SMRY
    I have 20 records in LAB_ST_TEMP
    when i am 8 records when i run the inner sql.
    but when i run whole sql with the update statement i am getting error.
    how can i re write this sql so that i will not get error

    A merge statement would work
    MERGE INTO lab_st_smry lls
    USING (SELECT llt.st_code
                 ,llt.st_name
                 ,llt.st_desc
                 ,llt.image
                 ,llt.st_id
                 ,llt.id
                 ,llt.assoc_disc
             FROM lab_st_temp llt
             INNER JOIN lab_temp lt ON lt.st_code = llt.st_code) lu
       ON (lu.st_id = lls.st_id)
       WHEN MATCHED THEN
         UPDATE
            SET st_code = lu.st_code
               ,st_name = lu.st_name
               ,st_desc = lu.st_desc
               ,image = lu.image
               ,id = lu.id
               ,dis_type = lu.assoc_disc
               ,zip_type = 1
               ,acte_ind = 1
               ,user = 'LabWork'
               ,update_date = sysdate;You could also add a WHERE clause to what you have now to insure you don't try to update any rows that don't exist in the other table
    UPDATE LAB_ST_SMRY LLS
    SET (ST_CODE, ST_NAME, ST_DESC,IMAGE, ST_ID, ID, DIS_TYPE, ZIP_TYPE,
    ACTE_IND, USER, UPDATE_DATE)
    = (SELECT LLT.ST_CODE, LLT.ST_NAME, LLT.ST_DESC, LLT.IMAGE, LLT.ST_ID, LLT.ID,
    LLT.ASSOC_DISC,1,1, 'LabWork', SYSDATE
    FROM LAB_ST_TEMP LLT
    INNER JOIN LAB_TEMP LT
    ON LLT.ST_CODE=LT.ST_CODE
    WHERE LLT.ST_ID=LLS.ST_ID
    GROUP BY LLT.ST_CODE, LLT.ST_NAME, LLT.ST_DESC, LLT.IMAGE, LLT.ST_ID, LLT.ID,LLT.ASSOC_DISC
    ) WHERE st_id IN
        (SELECT llt.st_id FROM lab_st_temp llt JOIN lab_temp lt ON llt.st_code = lt.st_code)Edited by: kendenny on Jan 27, 2011 9:50 AM

  • 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!

Maybe you are looking for

  • How to disable the new logon Window in Adobe Reader 11?

    Some times, some corporate guys get an idea - and no one is around to stop them. For some reason, there's now a logon window in Adobe Reader taking up 1/3 of the screen...and it can't be disabled. Which mor....person...ever thought of something like

  • Why can't I read one of these properties?

    This is just not the kind of problem I need with my cold fogged brain! I have this array collection [parentApplication.displayDraw.details]: (mx.collections::ArrayCollection)#0 filterFunction = (null) length = 1 list = (mx.collections::ArrayList)#1 l

  • Synching iPad 2 to a new MacBook Pro, November 2012.

    Bought iPad 2 in September 2011 and also installed iTunes on an old PC at that time. I now wish to 'retire' the PC as soon as I can verify that all important data is safely transferred to my new MB Pro acquired in September 2012. The PC's iTunes cont

  • Error code 1200 when checking updates in Reader X (10.1.0)

    Suddenly the Adobe Reader tells me I have to have administrator rights to check updates from the help menu. Never happened before. If I run Reader as an administrator everything is just fine. Not a big problem (I usually update Reader via Filehippo's

  • Heap allocation problem

    Hi all, I have a strange heap allocation problem with my application. I will try to explain what happens: My AWT-application reads data every second from a serial port and displays it. Max. heap size is set to -Xmx32m because the application has to r