Join SQL Statement

Hello all,
Good day.
I've one question on how to create the optimal index to support the below JOIN statement.
SELECT *      
FROM
     "TABLE1" T_1 INNER JOIN "TABLE2" T_2
     ON T_1.FIELD_JOIN1 = T_2. FIELD_JOIN1 AND
     ON T_1.FIELD_JOIN2 = T_2. FIELD_JOIN2
WHERE
     T_1.FIELD_WHERE3 and T_1. FIELD_WHERE4 and T_2. FIELD_WHERE5 and T_2. FIELD_WHERE6
I noticed that in many cases, there will be 2 indexes are created on each table: one index to support the fields in JOIN Condition and the other to support the WHERE Clause.
My initial thought is to combine the fields in the WHERE clause and JOIN Condition into one secondary index in order to make the index a 'covering index'.
My proposed indexes:
Index on TABLE1: MANDT, FIELD_WHERE3, FIELD_WHERE4, FIELD_JOIN1, FIELD_JOIN2
Index on TABLE2: MANDT, FIELD_WHERE5, FIELD_WHERE6, FIELD_JOIN1, FIELD_JOIN2
Let say all the fields in the JOIN Condition and WHERE Clause are very selective, is this recommended if we
1) Create an index which contains the fields for both JOIN condition and WHERE clause?
2) and the fields of the index will follow the above sequence, meaning the fields in WHERE clause are located at the beginning of the index?
Thanks,
KP

Hi Volker, Hi Harald,
Thanks for your reply.
I wrote one SQL statement and tested it in ST05 and the execution plan is as follow.
- how many rows in MSEG: 36,000,000 
- how many rows on WHERE MSEG: 4,000  << Smaller
- how many rows in MKPF: 5,700,000 
- how many rows on WHERE MKPF: 3,200,000
--> No of entries after joining the above tables plus the 'where' selection: 62 records
SELECT
FROM
  "MKPF" T_00
      INNER JOIN "MSEG" T_01
            ON T_01 . "MANDT" = '100' AND
                   T_00 . "MANDT" = T_01 . "MANDT" AND
                   T_00 . "MBLNR" = T_01 . "MBLNR" AND
                   T_00 . "MJAHR" = T_01 . "MJAHR"                           
WHERE
      T_00 . "MANDT" = '100' AND
      T_01 . "MATNR" = '000000111216070006' AND
      T_01 . "WERKS" = '1201' AND 
      T_00 . "BUDAT" >= '20090401'
From the execution plan above, the Outer table is MSEG and Nested Loop Join method is being used. I think correct access plan is used as only 62 records returned.
SELECT STATEMENT ( Estimated Costs = 19 , Estimated #Rows = 182 )
5 NESTED LOOPS
          ( Estim. Costs = 19 , Estim. #Rows = 182 )
            Estim. CPU-Costs = 1,646,549 Estim. IO-Costs = 19
2 TABLE ACCESS BY INDEX ROWID MSEG
              ( Estim. Costs = 18 , Estim. #Rows = 363 )
              Estim. CPU-Costs = 412,866 Estim. IO-Costs = 18
1 INDEX RANGE SCAN MSEG~M
( Estim. Costs = 1 , Estim. #Rows = 363 )
Search Columns: 3
Estim. CPU-Costs = 23,106 Estim. IO-Costs = 1
Access Predicates
4 TABLE ACCESS BY INDEX ROWID MKPF
Estim. CPU-Costs = 3,399 Estim. IO-Costs = 0
Filter Predicates
3 INDEX RANGE Scan MKPF~3
I think there is a room to further improve the above statement by
1) Append the fields in the JOIN condition to the index MSEG~M, so the field sequence of this index would be
     MANDT, MATNR , WERKS, MBLNR, MJAHR 
2) Append the fields (BUDAT) in the WHERE condition to the index MSEG~M, so the field sequence of this index would be
     MANDT, BUDAT, MBLNR, MJAHR      (The distinct number of field BUDAT is 840)
     --> I doubt that whether to put BUDAT at the beginning of the index because operator GE ">=" is used with BUDAT. Do you have any comment on this?
3) Let's assume BUDAT is used with Equal operator "=", will this field sequence look fine?
    MANDT, BUDAT, MBLNR, MJAHR
Your comments will be much appreciated. Thank you.
Best regards,
KP

Similar Messages

  • Please tell me the  Three table INNER JOIN Sql statement

    Hi experts,
      I got requirement like by using INNER JOIN i have to write the code in MY program i.e using 3 tables VBAK VBAP and VBUK.And the common field is VBELN .SO please give the  INNER JOIN SQL statement for above three tables...
    vbak-vbeln,erdat
    vbap-vbeln,posnr
    vbuk-vbeln,RFSTK
    Thanks in Advance

    hi guglani  please see my total code b.caus DATA is not extracting...once see the code  correct error.
    DATA:V_VBELN TYPE VBAK-VBELN.      "VBAK,VBAP AND VBUK
    SELECT-OPTIONS SORDER FOR V_VBELN.
    TYPES:BEGIN OF T_VBAK,
         VBELN TYPE VBELN_VA,
         ERDAT TYPE ERDAT,
      END OF T_VBAK.
    TYPES:BEGIN OF T_VBAP,
           VBELN TYPE VBELN_VA,
            POSNR TYPE POSNR_VA,
      END OF T_VBAP.
    TYPES:BEGIN OF T_VBUK,
        VBELN TYPE VBELN,
      RFSTK TYPE RFSTK,
      END OF T_VBUK.
    TYPES:BEGIN OF FS,
       VBELN TYPE VBELN_VA,
         ERDAT TYPE ERDAT,
    POSNR TYPE POSNR_VA,
      RFSTK TYPE RFSTK,
      END OF FS.
    DATA:WA1 TYPE T_VBAK,
         WA2 TYPE T_VBAP,
         WA3 TYPE T_VBUK,
         WA TYPE FS.
    DATA:ITAB1 TYPE TABLE OF T_VBAK,
          ITAB2 TYPE TABLE OF T_VBAP,
          ITAB3 TYPE TABLE OF T_VBUK,
          ITAB TYPE TABLE OF FS.
    select a~vbeln a~erdat b~posnr c~rfstk
           from vbak as a inner join vbAP as b on a~vbeln = b~vbeln
                          inner join vbuk as c on a~vbeln = c~vbeln
    into table itab
    where A~vbeln eq SORDER.
    IF NOT ITAB IS INITIAL.
      SORT ITAB BY VBELN.
    ENDIF.
    LOOP AT ITAB INTO WA.
       WRITE:/ WA-VBELN,WA-ERDAT,WA-rfstk.
       ENDLOOP.
       CLEAR WA.
       REFRESH ITAB.

  • SQL statement that includes LEFT & RIGHT JOIN in the same statement??? Help

    Hi,
    How an I write an SQL statement with a GROUP BY that will both (a) include the NULL value from the left hand table, but also (b) include ALL columns from the right hand table. It's like I need a LEFT JOIN and a RIGHT JOIN in the query at the same time.
    Here's an example of the 2 tables I have and the result I'm after. As you can see I want the NULL's from Expenses Table summed, as well as include all categories from the right hand table (i.e. even if there are no expenses against them)
    Table = Expenses
    Amount Category
    $10 1
    $20 2
    $30 1
    $40 NULL {i.e. not yet categorised}
    Table = Categories
    ID Title
    1 Food
    2 Entertainment
    3 Travel
    4 Personal
    REQUIRED RESULT
    Category Total
    Food 40
    Entertainment 20
    Travel 0
    Personal 0
    NULL 40
    Thanks

    SQL> create table expenses (amount,category)
      2  as
      3  select 10, 1 from dual union all
      4  select 20, 2 from dual union all
      5  select 30, 1 from dual union all
      6  select 40, null from dual
      7  /
    Table created.
    SQL> create table categories (id,title)
      2  as
      3  select 1, 'Food' from dual union all
      4  select 2, 'Entertainment' from dual union all
      5  select 3, 'Travel' from dual union all
      6  select 4, 'Personal' from dual
      7  /
    Table created.
    SQL> select c.title category
      2       , nvl(sum(e.amount),0) total
      3    from expenses e
      4         full outer join categories c on (e.category = c.id)
      5   group by c.id
      6       , c.title
      7   order by c.id
      8  /
    CATEGORY                                       TOTAL
    Food                                              40
    Entertainment                                     20
    Travel                                             0
    Personal                                           0
                                                      40
    5 rows selected.Regards,
    Rob.

  • Sql statement for join tables

    hi there..i need ur helps
    Here are my tables n column name for each tables
    a) rep_arrngt
    Name
    REP_ARRNGT_ID
    REP_ARRNGT_DESC
    REP_ARRNGT_TYPE
    ACCT_CAT
    DEF_INDUSTRY_CODE
    MEDIA_ID
    LANGUAGE_ID
    CURRENCY
    PAGE_ID
    b) bci_rep_arrng
    Name
    REP_ARRNGT_ID
    BCI
    SUB_SUM_CODE
    DP_SUB_SUM_CODE
    c) acct_rep_arrngt_link
    Name
    ACCT_NO
    REP_ARRNGT_ID
    DOC_TYPE
    LAST_BILL_DATE
    BILL_FREQUENCY
    SCALING
    EFF_FROM_DATE
    EFF_TO_DATE
    MEDIA_ID
    Actually, i want to get the unique value for sub_sum_code according to the bci..
    i already use join tables n here is my sql statement :
    SELECT T1.SUB_SUM_CODE,T1.BCI,T1.REP_ARRNGT_ID,T2.REP_ARRNGT_ID,T3.REP_ARRNGT_ID FROM BCI_REP_ARRNG T1, REP_ARRNGT T2, ACCT_REP_ARRNGT_LINK T3 WHERE T1.REP_ARRNGT_ID=T2.REP_ARRNGT_ID AND T2.REP_ARRNGT_ID=T3.REP_ARRNGT_ID AND BCI='TTA00F06'
    n my results is :
    SUB_SUM_CODE BCI REP_ARRNGT_ID
    TBGSR TTA00F06 R1
    TBGSR TTA00F06 R1
    TBGSR TTA00F06 R1
    TBGSR TTA00F06 R1
    I get the repeated results for sub_sum_code..
    so, what i need to do if i want only 1 row results like this :
    [u]SUB_SUM_CODE BCI REP_ARRNGT_ID
    TBGSR TTA00F06 R1
    i try to use group by, but i get the error..plz help me

    If you only want "to get the unique value for sub_sum_code according to the bci" then why are you joining the tables in the first place? Not knowing PKs etc you could just use DISTINCT in your select statement.
    SELECT DISTINCT T1.SUB_SUM_CODE,
                    T1.BCI
    FROM BCI_REP_ARRNG T1
    AND BCI='TTA00F06'

  • How to join multiple SQL statements?

    I'm try to combine four of the following SQL statements as one, and I basically want to group by the new combined sql statement by suspension
    Using: Oracle 10g
    Here's my sql statements/what I've tried but doesn't seem to work:
    select *
    from
    --NBA
    select
           decode (t.league_id, 1 , 'NBA') as League,
           t.moniker as First,
           t.Last_name as Last,
           (t.To_Team_Name || ' ' || To_Team_Nickname) as Team,
           count(*) Suspensions
    from   customer_data.cd_bk_trans t,
           customer_data.cd_bk_roster r
    where  t.player_id = r.player_id
    and    t.trans_type_id in (12,13,14)
    and    r.status = 'Y'
    and    r.league_id = 01
    group by t.league_id,t.last_name, t.moniker, t.to_team_name,t.to_team_nickname
    order by Suspensions desc
    union
    --MLB
    select
           decode (t.league_id, 7 , 'MLB') as League,
           t.moniker as First,
           t.Last_name as Last,
           (t.from_Team_Name || ' ' || from_Team_Nickname)as Team,
           count(*) Suspensions
    from   customer_data.cd_baseball_trans t,
           customer_data.cd_baseball_roster r
    where  t.player_id = r.player_id
    and    t.comments like '%Susp%'
    and    r.status = 'Y'
    and    r.league_id = 07
    group by t.league_id,t.last_name, t.moniker, t.from_team_name,t.from_team_nickname
    order by Suspensions desc
    union
    --NHL
    select
           decode (r.team_id,18, 'NHL') as League,
           t.fn as First,
           t.ln as Last,
           (t.from_Team_Name || ' ' || from_Team_Nickname)as Team,
           count(*) Suspensions
    from   customer_data.cd_nhl_trans t,
           customer_data.cd_nhl_roster r
    where  t.player_id = r.player_id
    and    t.trans_type in (10,11,12)
    and    r.status = 'Y'
    and    r.league_id = 18
    group by r.league_id, t.ln, t.fn, t.from_team_name,t.from_team_nickname
    order by Suspensions desc
    union
    --NFL
    select
           decode (t.league_id, 8, 'NFL') as League,
           t.moniker as First,
           t.last_name as Last,
           (t.from_Team_Name || ' ' || from_Team_Nickname)as Team,
           count(*) Suspensions
    from   customer_data.cd_football_trans t,
           customer_data.cd_football_roster r
    where  t.player_id = r.player_id
    and    t.trans_type_id in (24,25)
    and    r.status = 'Y'
    and    r.league_id = 8
    group by  t.league_id, t.last_name, t.moniker,           t.from_team_name,t.from_team_nickname
    order by  Suspensions desc
    Order by Suspensions desc

    Hi,
    Remove the ORDER BY clause in all the queries expcept lastone. Then it will work.
    You can have the ORDER BY clause in the last query of the inline view. Otherwise it will give the error.
    Run the query given below
    SELECT *
    FROM (
    --NBA
    SELECT decode(t.league_id, 1, 'NBA') AS league,
    t.moniker AS FIRST,
    t.last_name AS LAST,
    (t.to_team_name || ' ' || to_team_nickname) AS team,
    COUNT(*) suspensions
    FROM customer_data.cd_bk_trans t, customer_data.cd_bk_roster r
    WHERE t.player_id = r.player_id
    AND t.trans_type_id IN (12, 13, 14)
    AND r.status = 'Y'
    AND r.league_id = 01
    GROUP BY t.league_id,
    t.last_name,
    t.moniker,
    t.to_team_name,
    t.to_team_nickname
    UNION
    --MLB
    SELECT decode(t.league_id, 7, 'MLB') AS league,
    t.moniker AS FIRST,
    t.last_name AS LAST,
    (t.from_team_name || ' ' || from_team_nickname) AS team,
    COUNT(*) suspensions
    FROM customer_data.cd_baseball_trans t,
    customer_data.cd_baseball_roster r
    WHERE t.player_id = r.player_id
    AND t.comments LIKE '%Susp%'
    AND r.status = 'Y'
    AND r.league_id = 07
    GROUP BY t.league_id,
    t.last_name,
    t.moniker,
    t.from_team_name,
    t.from_team_nickname
    UNION
    --NHL
    SELECT decode(r.team_id, 18, 'NHL') AS league,
    t.fn AS FIRST,
    t.ln AS LAST,
    (t.from_team_name || ' ' || from_team_nickname) AS team,
    COUNT(*) suspensions
    FROM customer_data.cd_nhl_trans t, customer_data.cd_nhl_roster r
    WHERE t.player_id = r.player_id
    AND t.trans_type IN (10, 11, 12)
    AND r.status = 'Y'
    AND r.league_id = 18
    GROUP BY r.league_id,
    t.ln,
    t.fn,
    t.from_team_name,
    t.from_team_nickname
    UNION
    --NFL
    SELECT decode(t.league_id, 8, 'NFL') AS league,
    t.moniker AS FIRST,
    t.last_name AS LAST,
    (t.from_team_name || ' ' || from_team_nickname) AS team,
    COUNT(*) suspensions
    FROM customer_data.cd_football_trans t,
    customer_data.cd_football_roster r
    WHERE t.player_id = r.player_id
    AND t.trans_type_id IN (24, 25)
    AND r.status = 'Y'
    AND r.league_id = 8
    GROUP BY t.league_id,
    t.last_name,
    t.moniker,
    t.from_team_name,
    t.from_team_nickname
    ORDER BY suspensions DESC)
    ORDER BY suspensions DESC

  • How do I use SQL statements to perform calculations with form fields????

    Please help!!! I don't know how to use a SQL statement within my APEX form......
    My form is below. The user will enter the values in the form. Click on Submit. Then we need to run a SQL select statement with those values.
    Our form looks like this:
    Start_Date ____________
    Per_Period ____________
    Period ____________
    [Submit Button]
    The user will enter these 3 values in the form.
    This is an example of an user providing the values:
    Start_Date 03/14/08_______
    Per_Period $200.00________
    Period 4____________
    [Submit Button]
    Then they will click the Submit Button.
    The SQL statement (BELOW) returns output based on the users selections:
    START_DATE PER_PERIOD PERIOD
    14-MAR-2008 00:00 200 Week 1 of 4
    21-MAR-2008 00:00 200 Week 2 of 4
    28-MAR-2008 00:00 200 Week 3 of 4
    04-APR-2008 00:00 200 Week 4 of 4
    Total 800
    This is the full text of the SQL that makes the output above:
    with criteria as (select to_date('03/14/08', 'mm/dd/rr') as start_date,
    4 as periods,
    'Week' as period,
    200 per_period from dual),
    periods as (select 'Week' period, 7 days, 0 months from dual
    union all select 'BiWeek', 14, 0 from dual
    union all select 'Month', 0, 1 from dual
    union all select 'ByMonth', 0, 2 from dual
    union all select 'Quarter', 0, 3 from dual
    union all select 'Year', 0 , 12 from dual
    t1 as (
    select add_months(start_date,months*(level-1))+days*(level-1) start_date,
    per_period,
    c.period||' '||level||' of '||c.periods period
    from criteria c join periods p on c.period = p.period
    connect by level <= periods)
    select case grouping(start_date)
    when 1 then 'Total'
    else to_char(start_date)
    end start_date,
    sum(per_period) per_period,
    period
    from t1
    group by rollup ((start_date, period))
    THANKS VERY MUCH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    You're just doing a parameterized report, where the input fields are your parameters.
    Check out the Advanced Tutorial titled Parameterized Report here:
    http://download.oracle.com/docs/cd/E10513_01/doc/appdev.310/e10497/rprt_query.htm#BGBEEBJA
    Good luck,
    Stew

  • Help needed in SQL statement

    Hi,
    From the SQL statement below, i need help in explaining what does the line "WHERE ( lims_sys.result.result_template_id = lims_sys.result_template_limit.result_template_id (+))" do?
    This statement was written by a vendor and now i have problem displaying some new data. Only a portion of what i need is displayed.
    SELECT "LIMS_SYS"."RESULT"."DESCRIPTION",
    "LIMS_SYS"."RESULT_TEMPLATE_LIMIT"."NUMERIC_LIMIT",
    "LIMS_SYS"."RESULT"."FORMATTED_RESULT",
    "LIMS_SYS"."RESULT"."CONCLUSION",
    "LIMS_SYS"."RESULT_USER"."U_RESULT_SEQUENCE" ,
    "LIMS_SYS"."RESULT"."RESULT_ID"
    FROM "LIMS_SYS"."RESULT",
    "LIMS_SYS"."RESULT_TEMPLATE_LIMIT",
    "LIMS_SYS"."RESULT_USER",
    "LIMS_SYS"."ALIQUOT",
    "LIMS_SYS"."SAMPLE",
    "LIMS_SYS"."SDG",
    "LIMS_SYS"."TEST"
    WHERE ( lims_sys.result.result_template_id = lims_sys.result_template_limit.result_template_id (+)) and
    ( "LIMS_SYS"."RESULT"."RESULT_ID" = "LIMS_SYS"."RESULT_USER"."RESULT_ID" ) and
    ( "LIMS_SYS"."SDG"."SDG_ID" = "LIMS_SYS"."SAMPLE"."SDG_ID" ) and
    ( "LIMS_SYS"."SAMPLE"."SAMPLE_ID" = "LIMS_SYS"."ALIQUOT"."SAMPLE_ID" ) and
    ( "LIMS_SYS"."ALIQUOT"."ALIQUOT_ID" = "LIMS_SYS"."TEST"."ALIQUOT_ID" ) and
    ( "LIMS_SYS"."TEST"."TEST_ID" = "LIMS_SYS"."RESULT"."TEST_ID" ) and
    ( ( LIMS_SYS."SDG"."SDG_ID" = :sdg_id ) AND
    ( LIMS_SYS."RESULT"."STATUS" <> 'X' ) AND
    ( LIMS_SYS."RESULT"."REPORTED" = 'T' ) AND
    ( LIMS_SYS."RESULT_USER"."U_RESULT_CATEGORY" in ( 'Metal' , 'Mean Metal', 'Range Metal')) )
    Thanks for all your help.

    Hi,
    After WHERE .......... is indicates an OUTER Join condition.
    In this type of join, system retrieves the data for matched and
    as well as unmatched.
    Example:
    EMP table have a column DEPTNO with the data 10, 20, 30 (total rows=14)
    DEPT table have a column DEPTNO with the data 10, 20, 30, 40, 50 (total rows=5)
    If the WHERE clause contained EMP.DEPTNO(+) = DEPT.DEPTNO
    then the output contain the data relative to 10, 20, 30, 40, 50 (total rows = 16)
    i.e. 14 rows (with matching data) and 2 rows (with unmatching data)
    Regards,
    Sailaja

  • How to include 3 sql statements in a single procedure

    I have 3 SQL statements to create 3 tables:
    Table1:To get all the data from an ORIGIN table that have an expiration_dates between 02/01/2006 and 04/30/2006. This has all the customer data (customer_id, company, etc…)
    Table 2:Secondly I am getting all the customer_ids for February into another table called table2
    Table 3: Thirdly I am joining table 1 and table 2 on customer_id to get all the entries for the February customers those expire in February, March and April.
    Now I want to include all these in a procedure. Can I put all these together in 1 procedure so that I can run all these at once and have the results?
    Please throw some light on this.
    Thanks,
    Ac

    I hope this code will help you a little bit
    [email protected]> create table orgin(customer_id int, company varchar2(20), expiration_date date)
    2 /
    Table created.
    Elapsed: 00:00:01.06
    [email protected]> create table table2 (customer_id int, expiration_date date)
    2 /
    Table created.
    Elapsed: 00:00:00.01
    [email protected]> create table customers_table(customer_id int, cust_date date)
    2 /
    Table created.
    Elapsed: 00:00:00.01
    [email protected]> create table table3(customer_id int)
    2 /
    Table created.
    Elapsed: 00:00:00.01
    [email protected]> create table table1(customer_id int, company varchar2(20), expiration_date date)
    2 /
    Table created.
    create or replace procedure customers is
    begin
    -- table1
    insert into table1 select customer_id, company, expiration_date
    from orgin
    where expiration_date between to_date('01-02-2006','dd-mm-yyyy')
    and to_date('30-04-2006','dd-mm-yyyy');
    -- table2
    insert into table2 select customer_id, cust_date from customers_table
    where cust_date between to_date('01-02-2006','dd-mm-yyyy')
    and to_date('28-02-2006','dd-mm-yyyy');
    -- table3
    insert into table3 select a.customer_id from table1 a, table2 b
    where a.customer_id = b.customer_id;
    end;
    Best Regards
    Krystian Zieja / mob

  • Odd results from SQL statement in JSP

    Hi.
    Getting very strange results from my SQL statement housed in my JSP.
    the last part of it is like so:
    "SELECT DISTINCT AID, ACTIVE, REQUESTOR_NAME, ..." +
    "REQUESTOR_EMAIL" +
    " FROM CHANGE_CONTROL_ADMIN a INNER JOIN CHANGE_CONTROL_USER b " +
    "ON a.CHANGE_CTRL_ID = b.CHANGE_CTRL_ID " +
      " WHERE UPPER(REQUESTOR_NAME) LIKE ? ";   I've set the following variables and statements:
    String reqName = request.getParameter("requestor_name");
    PreparedStatement prepstmt = connection.prepareStatement(preparedQuery);
    prepstmt.setString(1, "%" + reqName.trim().toUpperCase() + "%");
    ResultSet rslts = prepstmt.executeQuery();
    rslts.next();
    int aidn = rslts.getInt(1);          
    int actbox = rslts.getInt(2);     String reqname = rslts.getString(3).toUpperCase();
    String reqemails = rslts.getString(4);
    String bizct = rslts.getString(5);
    String dept = rslts.getString(6);
    String loc = rslts.getString(7);
    Date datereq = rslts.getDate(8);
    String busvp = rslts.getString(9);
    AND SO ONSo then I loop it, or try to with the following:
    <%
      try {
      while ((rslts).next()) { %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    rslts.close();
    selstmt.close();
    catch(Exception ex){
         ex.printStackTrace();
         log("Exception", ex);
    %>AND so on, setting 13 getXXX methods of the 16 cols in the SQL statement.
    Trouble is I'm getting wildly inconsistent results.
    For example, typing 'H' (w/o quotes) will spit out 20 duplicate records of a guy named Herman, with the rest of his corresponding info correct, just repeated for some reason.
    Typing in 'He' will bring back the record twice (2 rows of the complete result set being queried).
    However, typing in 'Her' returns nothing. I could type in 'ell' (last 3 letters of his name, Winchell) and it will again return two duplicate records, but typing in 'hell' would return nothing.
    Am I omitting something crucial from the while statement that's needed to accurately print out the results set without duplicating it and that will ensure returning it?
    There's also records in the DB that I know are there but aren't being returned. Different names (i.e. Jennifer, Jesse, Jeremy) won't be returned by typing in partial name strings like Je.
    Any insight would be largely appreciated.
    One sidenote: I can go to SQL Plus and accurately return a results set through the above query. Having said that, is it possible the JDBC driver has some kind of issue?
    Message was edited by:
    bpropes20
    Message was edited by:
    bpropes20

    Am I omitting something crucial from the while
    statement that's needed to accurately print out the
    results set without duplicating it and that will
    ensure returning it?Yes.
    In this code, nothing ever changes the value of reqname or any of the other variables.
      while ((rslts).next()) { %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    } You code needs to be like this:while (rslts.next()) {
      reqname = rslts.getString(3).toUpperCase();
      reqemails = rslts.getString(4);
      bizct = rslts.getString(5);
      dept = rslts.getString(6);
      loc = rslts.getString(7);
      datereq = rslts.getDate(8);
      busvp = rslts.getString(9);
    %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    There's also records in the DB that I know are there
    but aren't being returned. Different names (i.e.
    Jennifer, Jesse, Jeremy) won't be returned by typing
    in partial name strings like Je.Well, you're half-right, your loop won't display all the rows in the result set, because you call rslts.next(); once immediately after executing the query. That advance the result set to the first row; when the loop is entered, it starts displaying at the 2nd row (or later if there are more next() calls in the code you omitted).

  • SQL Statement -- Throws GROUP BY issue on NVL

    Hey All,
    This is pretty much my first time tackling a very complex SQL Statement but the boss is adamant about it.
    Anyways here is the information. I have 3 Tables. Table one Contains Work Order Infromation that will be listed or grouped. Table 2 and Table 3 house information that needs to be summed (Estimate hours and Actual Hours).
    So my SQL Statement looked something like this... (Its a mess)
    select workorder.wolo3, workorder.wojp1, workorder.wonum, workorder.description, workorder.location, workorder.status, workorder.wopriority, workorder.targstartdate, workorder.reportdate, workorder.pmnum, workorder.schedstart, sum(labtrans.regularhrs + labtrans.premiumpayhours) as actualhours, sum(wplabor.quantity * wplabor.laborhrs) as estimatehrs
    from maximo.workorder left outer join maximo.labtrans on labtrans.regularhrs > 0 and labtrans.refwo = workorder.wonum and labtrans.siteid = workorder.siteid or labtrans.premiumpayratetype = 'MULTIPLIER' and labtrans.refwo = workorder.wonum and labtrans.siteid = workorder.siteid left outer join maximo.wplabor on wplabor.wonum = workorder.wonum and wplabor.siteid = workorder.siteid
    where workorder.istask=0 and workorder.siteid='NTS' and workorder.status in ('INPRG','SCHED') and workorder.crewid in ('MAINT','DAF') and workorder.schedstart <= TO_DATE('12-13-2009','MM-DD-YYYY') and wolo3 is not null group by workorder.wonum, workorder.status, workorder.wopriority, workorder.pmnum, workorder.location, workorder.description, workorder.targstartdate, workorder.reportdate, workorder.schedstart, workorder.wolo3, workorder.wojp1
    Now the problem is that the 2nd sum (Estimate Hrs) gets HUGE numbers if there are multiple rows in Actual Hours. So I did some searching. Seems that if I used the NVL function in the SQL Statement it would fix the issue...
    select workorder.wolo3, workorder.wojp1, workorder.wonum, workorder.description, workorder.location, workorder.status, workorder.wopriority, workorder.targstartdate, workorder.reportdate, workorder.pmnum, workorder.schedstart, sum(labtrans.regularhrs + labtrans.premiumpayhours) as actualhours,
    nvl((select sum(wplabor.quantity * wplabor.laborhrs) from maximo.wplabor where wplabor.wonum = workorder.wonum and wplabor.siteid = workorder.siteid),0)
    from maximo.workorder left outer join maximo.labtrans on labtrans.regularhrs > 0 and labtrans.refwo = workorder.wonum and
    labtrans.siteid = workorder.siteid or labtrans.premiumpayratetype = 'MULTIPLIER' and labtrans.refwo = workorder.wonum and
    labtrans.siteid = workorder.siteid
    where workorder.istask=0 and workorder.siteid='NTS' and workorder.status in ('INPRG','SCHED') and
    workorder.crewid in ('MAINT','DAF') and workorder.schedstart <= TO_DATE('12-13-2009','MM-DD-YYYY') and wolo3 is not null
    group by workorder.wonum, workorder.status, workorder.wopriority, workorder.pmnum, workorder.location, workorder.description, workorder.targstartdate, workorder.reportdate, workorder.schedstart, workorder.wolo3, workorder.wojp1
    However If get the error not a GROUP BY expression.
    I really need this to work. How can I get the NVL to work with out having to define a Group for it. The problem is that it is a "alias column" and you cannot Group by those fields. Frustation sets in... UGH!
    Thanks in Advance, Ben.

    Hi, Ben,
    Wlecome to the forum!
    user12273726 wrote:
    So my SQL Statement looked something like this... (Its a mess)You're right. Fix that first.
    Put each SELECT item, each condition, and each GROUP BY expression on a separate line. Indent to show here the clauses (SELECT, FROM, WHERE) are.
    For example:
    SELECT    workorder.wolo3
    ,       workorder.wojp1
    ,       workorder.wonum
    ,       workorder.description
    ,       workorder.location
    ,       workorder.status
    ,       workorder.wopriority
    ,       workorder.targstartdate
    ,       workorder.reportdate
    ,       workorder.pmnum
    ,       workorder.schedstart
    ,       SUM (labtrans.regularhrs + labtrans.premiumpayhours)     AS actualhours
    ,       SUM (wplabor.quantity * wplabor.laborhrs)          AS estimatehrs
    FROM                  maximo.workorder
    LEFT OUTER JOIN   maximo.labtrans     ON      labtrans.regularhrs         > 0
                                       AND     labtrans.refwo              = workorder.wonum
                             AND     labtrans.siteid              = workorder.siteid
                             OR     labtrans.premiumpayratetype = 'MULTIPLIER'     -- WARNING!  Don't mix AND and OR
                             AND     labtrans.refwo              = workorder.wonum
                             AND     labtrans.siteid              = workorder.siteid
    LEFT OUTER JOIN   maximo.wplabor     ON     wplabor.wonum              = workorder.wonum
                                       AND     wplabor.siteid              = workorder.siteid
    WHERE     workorder.istask      = 0
    AND       workorder.siteid       = 'NTS'
    AND       workorder.status       IN ('INPRG','SCHED')
    AND       workorder.crewid       IN ('MAINT','DAF')
    AND       workorder.schedstart   <= TO_DATE ('12-13-2009','MM-DD-YYYY')
    AND       wolo3                       IS NOT NULL
    GROUP BY  workorder.wonum
    ,            workorder.status
    ,       workorder.wopriority
    ,       workorder.pmnum
    ,       workorder.location
    ,       workorder.description
    ,       workorder.targstartdate
    ,       workorder.reportdate
    ,       workorder.schedstart
    ,       workorder.wolo3
    ,       workorder.wojp1
    ;When you post formatted text on this site, type these 6 characters:
    &#123;code&#125;
    (small letters only, inside curly brackets) before and after sections of formatted text, to preserve spacing.
    Now the problem is that the 2nd sum (Estimate Hrs) gets HUGE numbers if there are multiple rows in Actual Hours. Huge numbers are not necessarily wrong. Do yo mean the numbers computed by your query are much bigger than they are supposed to be?
    So I did some searching. Seems that if I used the NVL function in the SQL Statement it would fix the issue...
    select workorder.wolo3, workorder.wojp1, workorder.wonum, workorder.description, workorder.location, workorder.status, workorder.wopriority, workorder.targstartdate, workorder.reportdate, workorder.pmnum, workorder.schedstart, sum(labtrans.regularhrs + labtrans.premiumpayhours) as actualhours,
    nvl((select sum(wplabor.quantity * wplabor.laborhrs) from maximo.wplabor where wplabor.wonum = workorder.wonum and wplabor.siteid = workorder.siteid),0)
    ...It looks like you have a Chasm Trap, where you have multiple, independent one-to-many relationships on the same table, and the solution to aggregate them in separate queruies.
    It looks like you're trying to aggregate wplabor in scalar sub-queries, which makes the GROUP BY more complicated (as you discovered), and is also very inefficient.
    It would be easier to code and more efficient to run if you aggregated wplabor in a sub-query, and then joined to this sub-query (and not the actual wplabor table) in your main query.
    If you'd like help, post a little sample data (CREATE TABLE and INSERT statements) for all three tables, and the results you want from that data.
    Simplify as much as possible. Instead of GROUPing BY 11 columns, just GROUP BY, say, 3 columns: the 2 involved in the join condidiotns, and one more. Once you understand how to do this, adding the other expressions will be trivial.
    You can also simplify by ignoring, for now, the WHERE clause, and, therefore, the columns involved in the WHERE clause. It looks like that has nothing to do with the problem. Again, adding the conditions later will be trivial.

  • Selection Screen Parameters in SQL statements

    Very new ABAP programmer here, so sorry if this is a really dumb question.
    I'm trying to use my selection screen parameters to limit what is pulled in by my SQL statement (which seems to me to be a very logical thing to do).  But I'm having a problem, that when no values are entered in the parameters, no data is returned in the table instead of all the data being returned.
    Here is the code I have now:
      SELECT cname1 akostl aorgeh asname apernr bbegda bendda bstatu
             bconfl bmedcf breasn breman b~rqday
      INTO CORRESPONDING FIELDS OF TABLE it_record
       FROM ( ( pa0001 AS a
          INNER JOIN pa0672 AS b ON bpernr = apernr )
          INNER JOIN t500p AS c ON cpersa = awerks )
      WHERE  b~reman in so_reman
        AND a~kostl  in so_kostl
        AND a~orgeh = p_orgeh
        AND b~begda = p_begda
        AND b~statu = p_statu
        AND b~confl = p_confl
        AND b~medcf = p_medcf
        AND b~reasn = p_reasn
        AND b~rqday = p_rqday
        AND c~name1 = p_name1.
    Can anyone tell me what I'd need to do to make it return properly?

    When you use parameters and no value is entered, it is treated as initial value. and the select statement looks for the initial values for those fields in the tabl;e...
    you can make the parameters mandatory..then the user would be forced to enter something....
    also you could do the following..
    instead of parameters, use select-options with the addition no intervals and no extension, then practically it looks like a parameter but internally it is a select-option...
    and in the select statement, give conditions like....field1 in <s_option name>....in this case if the user is not entering a value ...it is treated as *...
    Thnaks & Regards,
    Renjith

  • SQL Statements in ABAP and meaning

    Hello Friends,
    Please, can anybody provide me a documentation on the different ABAP SQL statements and there usage/meanings.
    Thanks,
    Shreekant

    hi,
    goto abapdocu->abap Database access->open Sql you will get examples.
    for documnetation got se38->specify the command and press F1.
    SELECT:
    Put the curson on that word and press F1 . You can see the whole documentation for select statements.
    SELECT result
    FROM source
    INTO|APPENDING target
    [[FOR ALL ENTRIES IN itab] WHERE sql_cond]
    Effect
    SELECT is an Open-SQL-statement for reading data from one or several database tables into data objects.
    The select statement reads a result set (whose structure is determined in result ) from the database tables specified in source, and assigns the data from the result set to the data objects specified in target. You can restrict the result set using the WHERE addition. The addition GROUP BY compresses several database rows into a single row of the result set. The addition HAVING restricts the compressed rows. The addition ORDER BY sorts the result set.
    The data objects specified in target must match the result set result. This means that the result set is either assigned to the data objects in one step, or by row, or by packets of rows. In the second and third case, the SELECT statement opens a loop, which which must be closed using ENDSELECT. For every loop pass, the SELECT-statement assigns a row or a packet of rows to the data objects specified in target. If the last row was assigned or if the result set is empty, then SELECT branches to ENDSELECT . A database cursor is opened implicitly to process a SELECT-loop, and is closed again when the loop is ended. You can end the loop using the statements from section leave loops.
    Up to the INTO resp. APPENDING addition, the entries in the SELECTstatement define which data should be read by the database in which form. This requirement is translated in the database interface for the database system´s programming interface and is then passed to the database system. The data are read in packets by the database and are transported to the application server by the database server. On the application server, the data are transferred to the ABAP program´s data objects in accordance with the data specified in the INTO and APPENDING additions.
    System Fields
    The SELECT statement sets the values of the system fields sy-subrc and sy-dbcnt.
    sy-subrc Relevance
    0 The SELECT statement sets sy-subrc to 0 for every pass by value to an ABAP data object. The ENDSELECT statement sets sy-subrc to 0 if at least one row was transferred in the SELECT loop.
    4 The SELECT statement sets sy-subrc to 4 if the result set is empty, that is, if no data was found in the database.
    8 The SELECT statement sets sy-subrc to 8 if the FOR UPDATE addition is used in result, without the primary key being specified fully after WHERE.
    After every value that is transferred to an ABAP data object, the SELECT statement sets sy-dbcnt to the number of rows that were transferred. If the result set is empty, sy-dbcnt is set to 0.
    Notes
    Outside classes, you do not need to specify the target area with INTO or APPENDING if a single database table or a single view is specified statically after FROM, and a table work area dbtab was declared with the TABLES statement for the corresponding database table or view. In this case, the system supplements the SELECT-statement implicitly with the addition INTO dbtab.
    Although the WHERE-condition is optional, you should always specify it for performance reasons, and the result set should not be restricted on the application server.
    SELECT-loops can be nested. For performance reasons, you should check whether a join or a sub-query would be more effective.
    Within a SELECT-loop you cannot execute any statements that lead to a database commit and consequently cause the corresponding database cursor to close.
    SELECT - result
    Syntax
    ... lines columns ... .
    Effect The data in result defines whether the resulting set consists of multiple rows (table-like structure) or a single row ( flat structure). It specifies the columns to be read and defines their names in the resulting set. Note that column names from the database table can be changed. For single columns, aggregate expressions can be used to specify aggregates. Identical rows in the resulting set can be excluded, and individual rows can be protected from parallel changes by another program.
    The data in result consists of data for the rows lines and for the columns columns.
    SELECT - lines
    Syntax
    ... { SINGLE }
    | { { } } ... .
    Alternatives:
    1. ... SINGLE
    2. ... { }
    Effect
    The data in lines specifies that the resulting set has either multiple lines or a single line.
    Alternative 1
    ... SINGLE
    Effect
    If SINGLE is specified, the resulting set has a single line. If the remaining additions to the SELECT command select more than one line from the database, the first line that is found is entered into the resulting set. The data objects specified after INTO may not be internal tables, and the APPENDING addition may not be used.
    An exclusive lock can be set for this line using the FOR UPDATE addition when a single line is being read with SINGLE. The SELECT command is used in this case only if all primary key fields in logical expressions linked by AND are checked to make sure they are the same in the WHERE condition. Otherwise, the resulting set is empty and sy-subrc is set to 8. If the lock causes a deadlock, an exception occurs. If the FOR UPDATE addition is used, the SELECT command circumvents SAP buffering.
    Note
    When SINGLE is being specified, the lines to be read should be clearly specified in the WHERE condition, for the sake of efficiency. When the data is read from a database table, the system does this by specifying comparison values for the primary key.
    Alternative 2
    Effect
    If SINGLE is not specified and if columns does not contain only aggregate expressions, the resulting set has multiple lines. All database lines that are selected by the remaining additions of the SELECT command are included in the resulting list. If the ORDER BY addition is not used, the order of the lines in the resulting list is not defined and, if the same SELECT command is executed multiple times, the order may be different each time. A data object specified after INTO can be an internal table and the APPENDING addition can be used. If no internal table is specified after INTO or APPENDING, the SELECT command triggers a loop that has to be closed using ENDSELECT.
    If multiple lines are read without SINGLE, the DISTINCT addition can be used to exclude duplicate lines from the resulting list. If DISTINCT is used, the SELECT command circumvents SAP buffering. DISTINCT cannot be used in the following situations:
    If a column specified in columns has the type STRING, RAWSTRING, LCHAR or LRAW
    If the system tries to access pool or cluster tables and single columns are specified in columns.
    Note
    When specifying DISTINCT, note that you have to carry out sort operations in the database system for this.
    SELECT - columns
    Syntax
    | { {col1|aggregate( col1 )}
    {col2|aggregate( col2 )} ... }
    | (column_syntax) ... .
    Alternatives:
    1. ... *
    2. ... {col1|aggregate( col1 )}
    {col2|aggregate( col2 )} ...
    3. ... (column_syntax)
    Effect
    The input in columns determines which columns are used to build the resulting set.
    Alternative 1
    Effect
    If * is specified, the resulting set is built based on all columns in the database tables or views specified after FROM, in the order given there. The columns in the resulting set take on the name and data type from the database tables or views. Only one data object can be specified after INTO.
    Note
    If multiple database tables are specified after FROM, you cannot prevent multiple columns from getting the same name when you specify *.
    Alternative 2
    ... {col1|aggregate( col1 )}
    {col2|aggregate( col2 )} ...
    Effect
    A list of column labels col1 col2 ... is specified in order to build the resulting list from individual columns. An individual column can be specified directly or as an argument of an aggregate function aggregate. The order in which the column labels are specified is up to you and defines the order of the columns in the resulting list. Only if a column of the type LCHAR or LRAW is listed does the corresponding length field also have to be specified directly before it. An individual column can be specified multiple times.
    The addition AS can be used to define an alternative column name a1 a2 ... with a maximum of fourteen digits in the resulting set for every column label col1 col2 .... The system uses the alternative column name in the additions INTO|APPENDING CORRESPONDING FIELDS and ORDER BY. .
    http://help.sap.com/saphelp_nw04/helpdata/en/62/10a423384746e8bf5f15ccdd36e8b1/content.htm

  • Need help on how to code this SQL statement! (one key has leading zeros)

    Good day, everyone!
    First of all, I apologize if this isn't the best forum.  I thought of putting it in the SAP Oracle database forum, but the messages there seemed to be geared outside of ABAP SELECTs and programming.  Here's my question:
    I would like to join the tables FMIFIIT and AUFK.  The INNER JOIN will be done between FMIFIIT's MEASURE (Funded Program) field, which is char(24), and AUFK's AUFNR (Order Number) field, which is char(12).
    The problem I'm having is this:  All of the values in AUFNR are preceeded by two zeros.  For example, if I have a MEASURE value of '5200000017', the corresponding value in AUFNR is '005200000017'.  Because I have my SQL statement coded to just match the two fields, I obviously get no records returned because, I assume, of those leading zeros.
    Unfortunately, I don't have a lot of experience coding SQL, so I'm not sure how to resolve this.
    Please help!  As always, I will award points to ALL helpful responses!
    Thanks!!
    Dave

    >
    Dave Packard wrote:
    > Good day, everyone!
    > I would like to join the tables FMIFIIT and AUFK.  The INNER JOIN will be done between FMIFIIT's MEASURE (Funded Program) field, which is char(24), and AUFK's AUFNR (Order Number) field, which is char(12).
    >
    > The problem I'm having is this:  All of the values in AUFNR are preceeded by two zeros.  For example, if I have a MEASURE value of '5200000017', the corresponding value in AUFNR is '005200000017'.  Because I have my SQL statement coded to just match the two fields, I obviously get no records returned because, I assume, of those leading zeros.
    > Dave
    You can't do a join like this in SAP's open SQL.  You could do it in real SQL ie EXEC.... ENDEXEC by using SUSBTR to strip off the leading zeros from AUFNR but this would not be a good idea because a)  modifying a column in the WHERE clause will stop any index on that column being used and b) using real SQL rather than open SQL is really not something that should be encouraged for database portability reasons etc. 
    Forget about a database join and do it in two stages; get your AUFK data into an itab, strip off the leading zeros, and then use FAE to get the FMIFIIT data (or do it the other way round). 
    I do hope you've got an index on your FMIFIIT MEASURE field (we don't have one here); otherwise your SELECT could be slow if the table holds a lot of data.

  • Problem with sql statement after migration

    Hi, recently I copied a production database X to a remote location, to serve as a test upgrade database. Original is 32 bit and test database is 64 bit. After migration it turned out that one sql statement consumed much more CPU during EXECUTE phase than on production database. Explain plans are the same. Why CPU is different? How can I trace the problem?
    ORIGINAL SERVER TKPROF OUTPUT:
    call count cpu elapsed disk query current rows
    Parse 1 0.12 0.33 0 0 2 0
    Execute 1 542.60 2165.29 2 6 0 0
    Fetch 0 0.00 0.00 0 0 0 0
    total 2 542.73 2165.62 2 6 2 0
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 66 (SPB)
    Rows     Row Source Operation
          0  SORT UNIQUE (cr=6 pr=2 pw=0 time=719909655 us)
          0   FILTER  (cr=6 pr=2 pw=0 time=719909615 us)
          2    NESTED LOOPS  (cr=0 pr=0 pw=0 time=719895787 us)
          2     HASH JOIN  (cr=0 pr=0 pw=0 time=719881575 us)
          2      NESTED LOOPS  (cr=0 pr=0 pw=0 time=1210563833 us)
          2       NESTED LOOPS  (cr=0 pr=0 pw=0 time=1210549798 us)
          2        NESTED LOOPS  (cr=0 pr=0 pw=0 time=1210519159 us)
    330261         REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=29176788 us)
          2         REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=1177866001 us)
          2        REMOTE  TAMPROPVALUES (cr=0 pr=0 pw=0 time=30580 us)
          2       REMOTE  TREPVALUELISTITEMS (cr=0 pr=0 pw=0 time=13973 us)
    24542745      REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=638116004 us)
          2     REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=14154 us)
          2    INDEX RANGE SCAN IDX_PROCES_ID (cr=6 pr=2 pw=0 time=13706 us)(object id 546934)
    Rows     Execution Plan
          0  INSERT STATEMENT   MODE: ALL_ROWS
          0   SORT (UNIQUE)
          0    FILTER
          2     NESTED LOOPS
          2      HASH JOIN
          2       NESTED LOOPS
          2        NESTED LOOPS
          2         NESTED LOOPS
    330261          REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "ID","STATUS","STARTDATE"
                        FROM "DIALOG6"."TWFLPROCESSINSTANCES" "PI" WHERE
                          "STATUS"<>'A' AND "STATUS"<>'N' AND "STARTDATE">=:1-30
          2          REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","ROOTCITEM_ID",
                        "PRODUCT_ID","CONTRACT_ID" FROM
                        "DIALOG6"."TAMCONTRACTEDITEMD" "CI" WHERE "PRODUCT_ID"=
                          934 AND "CONTRACT_ID"=:1
          2         REMOTE OF 'TAMPROPVALUES' (REMOTE) [T6STDBY.WR]
                       SELECT /*+ OPAQUE_TRANSFORM */ "PROPERTY_ID",
                       "VALUEOBJECT_ID","CONTRACTEDITEM_ID","DTO","ISVALID"
                       FROM "DIALOG6"."TAMPROPVALUES" "TV" WHERE "DTO" IS NULL
                       AND "ISVALID"='Y' AND "CONTRACTEDITEM_ID"=:1 AND
                         "PROPERTY_ID"=930326
          2        REMOTE OF 'TREPVALUELISTITEMS' (REMOTE) [T6STDBY.WR]
                      SELECT /*+ OPAQUE_TRANSFORM */ "ID","NAME" FROM
                        "DIALOG6"."TREPVALUELISTITEMS" "TVL" WHERE "ID"=:1
    24542745       REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE) [T6STDBY.WR]
                     SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","CONTRACT_ID" FROM
                       "DIALOG6"."TAMCONTRACTEDITEMD" "CINAD"
          2      REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE) [T6STDBY.WR]
                    SELECT /*+ OPAQUE_TRANSFORM */ "ID" FROM
                    "DIALOG6"."TWFLPROCESSINSTANCES" "SYS_ALIAS_1" WHERE "ID"=
                      :1
          2     INDEX   MODE: ANALYZED (RANGE SCAN) OF 'IDX_PROCES_ID'
                    (INDEX)
    REMOTE SERVER TKPROF OUTPUT:
    call count cpu elapsed disk query current rows
    Parse 1 0.15 0.15 0 0 2 0
    Execute      1   1210.69    3831.70          0          6          0           0
    Fetch 0 0.00 0.00 0 0 0 0
    total 2 1210.85 3831.85 0 6 2 0
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 66 (SPB)
    Rows     Row Source Operation
          0  SORT UNIQUE (cr=6 pr=0 pw=0 time=681448432 us)
          0   FILTER  (cr=6 pr=0 pw=0 time=681448397 us)
          2    NESTED LOOPS  (cr=0 pr=0 pw=0 time=681448144 us)
          2     HASH JOIN  (cr=0 pr=0 pw=0 time=681443808 us)
          2      NESTED LOOPS  (cr=0 pr=0 pw=0 time=168646003 us)
          2       NESTED LOOPS  (cr=0 pr=0 pw=0 time=168636029 us)
          2        NESTED LOOPS  (cr=0 pr=0 pw=0 time=168580989 us)
    327667         REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=9177863 us)
          2         REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=158011360 us)
          2        REMOTE  TAMPROPVALUES (cr=0 pr=0 pw=0 time=55007 us)
          2       REMOTE  TREPVALUELISTITEMS (cr=0 pr=0 pw=0 time=9947 us)
    24542745      REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=3509657414 us)
          2     REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=4309 us)
          2    INDEX RANGE SCAN IDX_PROCES_ID (cr=6 pr=0 pw=0 time=160 us)(object id 552075)
    Rows     Execution Plan
          0  INSERT STATEMENT   MODE: ALL_ROWS
          0   SORT (UNIQUE)
          0    FILTER
          2     NESTED LOOPS
          2      HASH JOIN
          2       NESTED LOOPS
          2        NESTED LOOPS
          2         NESTED LOOPS
    327667          REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "ID","STATUS","STARTDATE"
                        FROM "DIALOG6"."TWFLPROCESSINSTANCES" "PI" WHERE
                          "STATUS"<>'A' AND "STATUS"<>'N' AND "STARTDATE">=:1-30
          2          REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","ROOTCITEM_ID",
                        "PRODUCT_ID","CONTRACT_ID" FROM
                        "DIALOG6"."TAMCONTRACTEDITEMD" "CI" WHERE "PRODUCT_ID"=
                          934 AND "CONTRACT_ID"=:1
          2         REMOTE OF 'TAMPROPVALUES' (REMOTE) [T6STDBY.WR]
                       SELECT /*+ OPAQUE_TRANSFORM */ "PROPERTY_ID",
                       "VALUEOBJECT_ID","CONTRACTEDITEM_ID","DTO","ISVALID"
                     FROM "DIALOG6"."TAMPROPVALUES" "TV" WHERE "DTO" IS NULL
                       AND "ISVALID"='Y' AND "CONTRACTEDITEM_ID"=:1 AND
                         "PROPERTY_ID"=930326
          2        REMOTE OF 'TREPVALUELISTITEMS' (REMOTE) [T6STDBY.WR]
                      SELECT /*+ OPAQUE_TRANSFORM */ "ID","NAME" FROM
                        "DIALOG6"."TREPVALUELISTITEMS" "TVL" WHERE "ID"=:1
    24542745       REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE) [T6STDBY.WR]
                     SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","CONTRACT_ID" FROM
                       "DIALOG6"."TAMCONTRACTEDITEMD" "CINAD"
          2      REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE) [T6STDBY.WR]
                    SELECT /*+ OPAQUE_TRANSFORM */ "ID" FROM
                    "DIALOG6"."TWFLPROCESSINSTANCES" "SYS_ALIAS_1" WHERE "ID"=
                      :1
          2     INDEX   MODE: ANALYZED (RANGE SCAN) OF 'IDX_PROCES_ID'
                    (INDEX)Edited by: Przemek P on 2012-01-27 07:40
    Edited by: Przemek P on 2012-01-27 07:50

    Could you please edit your post and use \ tags so the output is more user friendly?
    Type: \Your Code Here\It will display as:Your Code Here                                                                                                                                                                                                                                                                                                                                                                       

  • ABAP Standards for a SQL statement

    Hi,
    I have a Native SQL statement in my ABAP user exit, pls. edit into a Open SQL,
    SELECT v1~tknum v1~tsnum
          INTO TABLE t_vtts
          FROM vtts AS v1
          FOR ALL ENTRIES IN t_shipment_del
          WHERE v1~tknum = t_shipment_del-tknum AND
                v1~vstel = rv_shppt          AND
                v1~kunnz = rv_shipto         AND
                v1~tsrfo = c_one             AND
                EXISTS ( SELECT addrnumber
                           FROM adrc CLIENT SPECIFIED
                           WHERE client     =  v1~mandt AND
                                 addrnumber =  v1~adrnz AND
                                 date_from  <= sy-datum AND
                                 date_to    >= sy-datum AND
                                 post_code1 =  rv_post_code1 ).
    Thank you

    Hhmm, for proper performance analysis we'd need some further details. Looking at your query I doubt that the following alternative helps, but you can give it a try, because subqueries are not always optimal:
      SELECT tknum tsnum INTO TABLE t_vtts
             FROM vtts INNER JOIN adrc ON
                  vtts~adrnz = adrc~addrnumber
             FOR ALL entries IN t_shipment_del
             WHERE tknum      = t_shipment_del-tknum AND
                   vstel      = rv_shppt             AND
                   kunnz      = rv_shipto            AND
                   tsrfo      = c_one                AND
                   post_code1 = rv_post_code1.
    You might need to add the condition on the address dates, but in any system I've checked so far, the ADRC-FROM date was always 00010101 and there was only one entry per address number (so if required, add it back).
    For performance tuning requests you should try to provide some background information, like:
    <ol>
    <li>How many entries are you your table T_SHIPMENT_DEL</li>
    <li>How many entries match your conditions on VTTS</li>
    <li>How many entries get dropped because of the condition on postal code</li>
    <li>Do a SQL trace and provide information about the execution plan chosen by the database</li>
    </ol>
    Also, you might want to consider moving your question to the forum.
    Cheers, harald

Maybe you are looking for