Joins and where

When two tables are joined and there is a where predicate, what is done first ?
1) the WHERE in order to filter the records being joined.
2) the JOIN and after both tables are together with all their records Oracle filters according to the where predicate ?
Thanks.

The SQL and PL/SQL forum is at:
PL/SQL
You may reach a wider audience if you post your SQL language
question there.
-- CJ

Similar Messages

  • Absolute dynamic select query with dynamic join and where

    Has anyone ever tried creating an absolutely dynamic SELECT query with dynamic Join and Where conditions.
    I have a requirement of creating such a query in an Utility Class, and i have written the code. But its throwing my sysntax errors.
    Please let me know where am I going wrong OR is it really possible to create such a dynamic Query??
        SELECT (FIELDS) INTO TABLE IT_TABLES
          FROM ( (ME->TABLE1)  inner join ( me->table2 )
          on ( on_condition ) )
          WHERE (me->where_fields).
    Ags.

    It worked for me in a following way:
    select * into corresponding fields of table <result_table>
            from (join_string)
            where (l_where).
    Where the contents of join_string were dynamically build using concatenation. So it will be something like
    concatenate ME->TABLE1 'as a INNER JOIN' me->table2 'as b ON (' into join_string separated by space.
    <...>
    add here matching/reference colums, something like
    concatenate 'a~' me->TABLE1_JOIN_COL into temp1.
    concatenate 'b~' me->TABLE2_JOIN_COL into temp2.
    concatenate join_string temp1 '=' temp2 into join_string separated by space.
    <...>
    concatenate join_string ')' into join_string separated by space.
    And then use similar approach for l_where variable.

  • CONNECT BY with CROSS JOIN and WHERE not executing as described in doc

    Hello all,
    please see these two statements. They are the same, but the 1st uses t1 INNER JOIN t2 while the snd uses a CROSS JOIN with WHERE.
    The 2nd statement shows one row more than the first, but the CROSS JOIN with WHERE is the same as the INNER JOIN.
    The result would be OK if Oracle did:
    JOIN -> CONNECT BY PRIOR -> WHERE
    But according to the docs it does:
    JOIN (and WHEREs for JOINS) -> CONNECT BY PRIOR -> Rest of WHERE
    See http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries003.htm#SQLRF52332 for details. There it says:
    Oracle processes hierarchical queries as follows:
    A join, if present, is evaluated first, whether the join is specified in the FROM clause or with WHERE clause predicates.
    The CONNECT BY condition is evaluated.
    Any remaining WHERE clause predicates are evaluated.
    +.....+
    Is this a bug? I'd say yes, because it differs from the docs and it also is not what people are used to ("a,b WHERE" is the same as "a INNER JOIN b").
    Thanks,
    Blama
    --Statement 1:
    WITH t1
    AS
    (SELECT 1 a, 2 b FROM DUAL UNION ALL
    SELECT 2 a, 3 b FROM DUAL UNION ALL
    SELECT 3 a, 4 b FROM DUAL UNION ALL
    SELECT 4 a, 5 b FROM DUAL UNION ALL
    SELECT 5 a, 6 b FROM DUAL),
    t2 AS
    (SELECT 1 c FROM DUAL UNION ALL
    SELECT 2 c FROM DUAL UNION ALL
    SELECT 3 c FROM DUAL UNION ALL
    SELECT 5 c FROM DUAL)
    SELECT DISTINCT t1.a, t2.c, t1.b, level, SYS_CONNECT_BY_PATH(t1.a, '/') Path
    FROM t1 INNER JOIN t2
    ON t1.a = t2.c
    CONNECT BY t1.a = PRIOR t1.b
    START WITH t1.a = 1
    ORDER BY
    1,2,3;
    --Result:
    --1     1     2     1     /1
    --2     2     3     2     /1/2
    --3     3     4     3     /1/2/3
    --Statement 2:
    WITH t1
    AS
    (SELECT 1 a, 2 b FROM DUAL UNION ALL
    SELECT 2 a, 3 b FROM DUAL UNION ALL
    SELECT 3 a, 4 b FROM DUAL UNION ALL
    SELECT 4 a, 5 b FROM DUAL UNION ALL
    SELECT 5 a, 6 b FROM DUAL),
    t2 AS
    (SELECT 1 c FROM DUAL UNION ALL
    SELECT 2 c FROM DUAL UNION ALL
    SELECT 3 c FROM DUAL UNION ALL
    SELECT 5 c FROM DUAL)
    SELECT DISTINCT t1.a, t2.c, t1.b, level, SYS_CONNECT_BY_PATH(t1.a, '/') Path
    FROM t1 CROSS JOIN t2
    WHERE t1.a = t2.c
    CONNECT BY t1.a = PRIOR t1.b
    START WITH t1.a = 1
    ORDER BY
    1,2,3;
    --Result:
    --1     1     2     1     /1
    --2     2     3     2     /1/2
    --3     3     4     3     /1/2/3
    --5     5     6     5     /1/2/3/4/5My details:
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE     11.2.0.2.0     Production
    TNS for Solaris: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production

    blama wrote:
    Hello Paul,
    that means that "a,b" isn't the same as "a CROSS JOIN b".
    I don't think that that is really the case.
    Do you have docs on this one?No explicit docs just (my) logic - having said that, I suppose it is implied that if you are doing ANSI style joins, it's not the where clauses that
    are specifying the join.
    If you do t1,t2 where t1.a=t2.a then Oracle figures out the kind of join from the (relevant) where clauses and treats the other where clauses after the CONNECT BY.
    If you do t1 cross join t2 where t1.a=t2.a then you are saying the join is completely specified by the CROSS JOIN - i.e it's Cartesian. Oracle doesn't look at the where clauses for this. Therefore
    all where clauses are treated as 'other' and are evaluated after the CONNECT BY.
    So, in my mind it's 10g that has the bug.

  • Joins and where execution

    When two tables are joined and there is a where predicate, what is done first ?
    1) the WHERE in order to filter the records being joined.
    2) the JOIN and after both tables are together with all their records Oracle filters according to the where predicate ?
    Thanks.

    It depends on the information available to the optimizer. In most cases, Oracle will use any predictes on the driving table to filter rows from that table before joining to the other table. Whether it applies predicates to the other table before or after joining depends on the selectivity of the predicate implied by the join compared to any other predicates.
    John

  • Oracle UPDATE syntax with JOIN and WHERE clause

    I need to update one of my tables, and can't seem to get the syntax right. I've tried a 4 different approaches, but not having any luck.  Any help would be greatly appreciated.
    Attempt #1: Error: SQL command not properly ended
    UPDATE TESTDTA.F4941
    SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM
    FROM TESTDTA.F4941
    INNER JOIN TESTDTA.F4981
    ON TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    WHERE TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS';
    Attempt #2: Error report: SQL Error: ORA-00904: "TESTDTA"."F4981"."FHUOM": invalid identifier 00904. 00000 - "%s: invalid identifier"
    UPDATE (SELECT TESTDTA.F4941
    FROM TESTDTA.F4941
    INNER JOIN TESTDTA.F4981
    ON TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    WHERE TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS')
    SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM
    Attempt #3: Error report: SQL Error: ORA-00904: "TESTDTA"."F4941": invalid identifier 00904. 00000 - "%s: invalid identifier"
    UPDATE (SELECT *
    FROM TESTDTA.F4941
    INNER JOIN TESTDTA.F4981
    ON TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    WHERE TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS')
    SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM;
    Attempt #4: Error: ORA-00925: missing INTO keyword 00925. 00000 - "missing INTO keyword"
    MERGE TESTDTA.F4941
    USING TESTDTA.F4981
    ON (TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    AND TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS'
    WHEN MATCHED THEN
    UPDATE SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ
       ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM;

    thank you for the attempt, but I get this error trying your method...
    Error report:
    SQL Error: ORA-01779: cannot modify a column which maps to a non key-preserved table
    01779. 00000 -  "cannot modify a column which maps to a non key-preserved table"
    *Cause:    An attempt was made to insert or update columns of a join view which
               map to a non-key-preserved table.
    *Action:   Modify the underlying base tables directly.
    as for the background of what I'm trying to...
    I have 2 tables, one that has shipments with no miles (F4941 / Routing Steps), and another that does have miles (F4981 / Freight Audit History).
    I want to update the miles & UnitOfMeasure columns for all shipments in the F4941 that currently have 0 miles with the miles found in the F4981 which are connected by Shipment number.  Here's my same script, with simpler naming.
    UPDATE RoutingSteps
    SET RoutingSteps.Miles=FreightAuditHistory.Miles,RoutingSteps.UnitOfMeasure=FreightAuditHistory.UnitOfMeasure
    FROM RoutingSteps
    INNER JOIN FreightAuditHistory
    ON RoutingSteps.ShipmentNumber  = FreightAuditHistory.ShipmentNumber
    WHERE RoutingSteps.ShipmentNumber = 647143
    AND RoutingSteps.Miles = 0
    AND RoutingSteps.ShipmentDate  > 110365
    AND FreightAuditHistory.Category  = 'DIS';
    hope this helps visualize my intent

  • Left join and where clause with not equal ( ) returns too many rows

    Say I have something like this
    Table A
    =========
    Id
    OrderNum
    Date
    StoreName
    AddressKey
    Table B
    ========
    Id
    StreetNumber
    City
    State
    select a.* from [Table A] a
    left join [Table B] b on a.AddressKey = b.Id
    where a.StoreName <> 'Burger place'
    The trouble is that the above query still returns rows that have StoreName = 'Burger place'
    One way Ive handled this is to use a table expression, select everything into that, then select from the CTE and apply the filter there.  How could you handle it in the same query however?

    Hi Joe,
    Thanks for your notes.
    INT SURROGATE PRIMARY KEY provides a small footprint JOIN ON column. Hence performance gain and simple JOIN programming.  In the Addresses table, address_id is 4 bytes as opposed to 15 bytes san. Similarly for the Orders table.
    INT SURROGATE PRIMARY KEY is a meaningless number which can be duplicated at will in other tables as FOREIGN KEY.  Having a meaningful PRIMARY KEY violates the RDBMS basics about avoiding data duplication.  If I make CelebrityName (Frank Sinatra)
    a PRIMARY KEY, I have to duplicate "Frank Sinatra" as an FK wherever it needed as opposed to duplicating SURROGATE PRIMARY KEY CelebrityID (79) a meaningless number.
    This is how we design in SQL Server world.
    QUOTE from Wiki: "
    Advantages[edit]
    Immutability[edit]
    Surrogate keys do not change while the row exists. This has the following advantages:
    Applications cannot lose their reference to a row in the database (since the identifier never changes).
    The primary or natural key data can always be modified, even with databases that do not support cascading updates across related
    foreign keys.
    Requirement changes[edit]
    Attributes that uniquely identify an entity might change, which might invalidate the suitability of natural keys. Consider the following example:
    An employee's network user name is chosen as a natural key. Upon merging with another company, new employees must be inserted. Some of the new network user names create conflicts because their user names were generated independently (when the companies
    were separate).
    In these cases, generally a new attribute must be added to the natural key (for example, an
    original_company column). With a surrogate key, only the table that defines the surrogate key must be changed. With natural keys, all tables (and possibly other, related software) that use the natural key will have to change.
    Some problem domains do not clearly identify a suitable natural key. Surrogate key avoids choosing a natural key that might be incorrect.
    Performance[edit]
    Surrogate keys tend to be a compact data type, such as a four-byte integer. This allows the database to query the single key column faster than it could multiple columns. Furthermore a non-redundant distribution of keys causes the resulting
    b-tree index to be completely balanced. Surrogate keys are also less expensive to join (fewer columns to compare) than
    compound keys.
    Compatibility[edit]
    While using several database application development systems, drivers, and
    object-relational mapping systems, such as
    Ruby on Rails or
    Hibernate, it is much easier to use an integer or GUID surrogate keys for every table instead of natural keys in order to support database-system-agnostic operations and object-to-row mapping.
    Uniformity[edit]
    When every table has a uniform surrogate key, some tasks can be easily automated by writing the code in a table-independent way.
    Validation[edit]
    It is possible to design key-values that follow a well-known pattern or structure which can be automatically verified. For instance, the keys that are intended to be used in some column of some table might be designed to "look differently from"
    those that are intended to be used in another column or table, thereby simplifying the detection of application errors in which the keys have been misplaced. However, this characteristic of the surrogate keys should never be used to drive any of the logic
    of the applications themselves, as this would violate the principles of
    Database normalization"
    LINK: http://en.wikipedia.org/wiki/Surrogate_key
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • Join and Multiple where clauses: which is better??

    There was an argument between a colleague and I. He prefers building his views joining many tables with many where clause while I am cute with my join which is simpler and more understandable for me. So, it started an argument on which is a superior way of joining tables.
    I will actually like to know we is faster and better: using JOINs or using multiple where clauses to retrieve values from multiple tables.?

    Dave:
    "Are we talking about the difference between Oracle Joins and ANSI Joins?
    e.g.
    Select d.dept_name, e.emp_name
    from dept d, emp e
    where d.dept_id = e.dept_id"
    That is not really an "Oracle Join". That syntax works on just about every SQL database I have ever worked with. The (+) syntax for an outer join is Oracle specific, but some other databases use a similar style for outer joins (something like a.c += b.c or a.c *= b.c).
    OP:
    There are things you can do with the ANSI style syntax that either cannot be done, or cannot be done as easily, with Oracle's syntax. Most notably, outer joining one table to more than one other tables, and FULL OUTER joins.
    Having said that, in my experience, both are rather rare occurrences, so I tend to stick to doing the jopins in the WHERE clause because that is what I am used to.
    John

  • Using join and batch reading in the same query

    Hi,
    I wonder if it is possible to use "Joining" and "batch reading" in the same query.
    For example I Have
    A -> 1-1 B
    A -> 1-1 B
    B -> 1-M C
    This is the case where I have two separate 1-1 relationships to the same class B from A. Toplink 10.0.3 can manage it nicely through joining.
    Now, I would like to read a set of As (with its 2 Bs) and all Cs for each B.
    It seems that the following configuration does not work:
    A -> 1-1 B (use joining)
    A -> 1-1 B (use joining)
    B -> 1-M C (Batch read)
    Any help would be greatly appreciated
    Tony.

    James,
    Would you be so kind to look at the following code?
    Am I formulating it correctly to achieve my desired behavior?
    Trip.class -> 1-1 PickupStop
    Trip.class -> 1-1 DropoffStop
    PickupStop and DropoffStop extend Stop and use same table (STOP)
    Stop -> 1-M StopEvents
    I would like to fetch all Trips, with their Stops and all StopEvents in 2 queries:
    1. Trip joined with Stop
    2. Batchread StopEvents
    Code:
    ReadAllQuery raq = new ReadAllQuery(Trip.class);
    Expression qexp1 = new ExpressionBuilder();
    Expression qexp2 = new ExpressionBuilder();
    raq.addJoinedAttribute("pickupStop");
    raq.addJoinedAttribute("dropoffStop");
    raq.addBatchReadAttribute(qexp1.get("pickupStop").get("vStopEvents"));
    raq.addBatchReadAttribute(qexp2.get("dropoffStop").get("vStopEvents"));

  • Outer Join with Where Clause in LTS

    HI all,
    I have a requirement like this in ANSI SQL:
    select p1.product_id, p1.product_name, p2.product_group
    from product p1 left outer join product_group p2 on p1.product_id = p2.product_id
    and p2.product_group = 'NEW'
    In Regular SQL:
    select p1.product_id, p1.product_name, p2.product_group
    from product p1, product_group p2
    WHERE p1.product_id *= p2.product_id and p2.product_group = 'NEW'
    In OBIEE, I am using a left outer join between these two in Logical table Source, and also, Gave
    p2.product_group = 'NEW' in WHERE clause of LTS.
    This doesn't seem to solve purpose.
    Do you have any idea how to convert WHERE clause in physical query that OBIEE is generating to something like
    product p1 left outer join product_group p2 on p1.product_id = p2.product_id AND p2.product_group = 'NEW'
    I am using Version 10.1.3.4.1
    Creating an Opaque view would be my last option though.

    Hello
    I have read your post and the responses as well. and I understand that you have issues with the Outer Join with where Clause in LTS.
    Try this solution which worked for me (using your example ) -
    1. In the Physical Layer created a Complex join between PRODUCT and PRODUCT_GROUP tables and use this join relationship :
    PRODUCT.PROD_ID = PRODUCT_GROUP.PROD_ID  AND  PRODUCT_GROUP.GROUP_NAME = 'MECHANICAL' 
    2. In the General Tab of PRODUCT table LTS add PRODUCT_GROUP  table and select Join Type as Left Outer Join.
    3. Check Consistency and make sure there are no errors .
    when you run a request you should see the following query generated -
    select distinct T26908.PROD_ID as c1,
         T26908.PROD_NAME as c2,
         T26912.GROUP_NAME as c3
    from
         PRODUCT T26908 left outer join PRODUCT_GROUP T26912 On T26908.PROD_ID = T26912.PROD_ID and T26912.GROUP_NAME = 'MECHANICAL'
    order by c1, c2, c3
    Hope this works for you. If it does please mark this response as 'Correct' .
    Good Luck.

  • What is joins?where we use it. is it DD concept? abap

    hi abapers,
    what is joins?where we use it. is it DD concept?
      regards,
      anjan

    hi srinivas.
    chk this simple example.
    u will get good idea.
    table emp
    empno name
    a sasi
    b xxx
    c yyy
    table sal
    empno salary
    a 1000
    b 2000
    Inner join
    select eempno ename
    s~sal
    into table int_table
    from emp as e
    inner join sal
    on
    eempno = sempno.
    if you made inner join between table a and b by emp no
    the selection retrives only if the condition satisfy the output will be
    a sasi 1000
    b xxx 2000
    Outer join
    select eempno ename
    s~sal into table  int_table
    from emp as e
    LEFT OUTER JOIN sal
    on
    eempno = sempno.
    if you made outer join (left /right ) the left table kept as it is the
    if the condition satisfy the right table entries will fetch else leave it blank
    the output will be
    a sasi a 1000
    b xxx b 2000
    c yyy
    rgds
    anver
    if helped mark points

  • Need help in optimizing the query with joins and group by clause

    I am having problem in executing the query below.. it is taking lot of time. To simplify, I have added the two tables FILE_STATUS = stores the file load details and COMM table that is actual business commission table showing records successfully processed and which records were transmitted to other system. Records with status = T is trasnmitted to other system and traansactions with P is pending.
    CREATE TABLE FILE_STATUS
    (FILE_ID VARCHAR2(14),
    FILE_NAME VARCHAR2(20),
    CARR_CD VARCHAR2(5),
    TOT_REC NUMBER,
    TOT_SUCC NUMBER);
    CREATE TABLE COMM
    (SRC_FILE_ID VARCHAR2(14),
    REC_ID NUMBER,
    STATUS CHAR(1));
    INSERT INTO FILE_STATUS VALUES ('12345678', 'CM_LIBM.TXT', 'LIBM', 5, 4);
    INSERT INTO FILE_STATUS VALUES ('12345679', 'CM_HIPNT.TXT', 'HIPNT', 4, 0);
    INSERT INTO COMM VALUES ('12345678', 1, 'T');
    INSERT INTO COMM VALUES ('12345678', 3, 'T');
    INSERT INTO COMM VALUES ('12345678', 4, 'P');
    INSERT INTO COMM VALUES ('12345678', 5, 'P');
    COMMIT;Here is the query that I wrote to give me the details of the file that has been loaded into the system. It reads the file status and commission table to show file name, total records loaded, total records successfully loaded to the commission table and number of records that has been finally transmitted (status=T) to other systems.
    SELECT
        FS.CARR_CD
        ,FS.FILE_NAME
        ,FS.FILE_ID
        ,FS.TOT_REC
        ,FS.TOT_SUCC
        ,NVL(C.TOT_TRANS, 0) TOT_TRANS
    FROM FILE_STATUS FS
    LEFT JOIN
        SELECT SRC_FILE_ID, COUNT(*) TOT_TRANS
        FROM COMM
        WHERE STATUS = 'T'
        GROUP BY SRC_FILE_ID
    ) C ON C.SRC_FILE_ID = FS.FILE_ID
    WHERE FILE_ID = '12345678';In production this query has more joins and is taking lot of time to process.. the main culprit for me is the join on COMM table to get the count of number of transactions transmitted. Please can you give me tips to optimize this query to get results faster? Do I need to remove group and use partition or something else. Please help!

    I get 2 rows if I use my query with your new criteria. Did you commit the record if you are using a second connection to query? Did you remove the criteria for file_id?
    select carr_cd, file_name, file_id, tot_rec, tot_succ, tot_trans
      from (select fs.carr_cd,
                   fs.file_name,
                   fs.file_id,
                   fs.tot_rec,
                   fs.tot_succ,
                   count(case
                            when c.status = 'T' then
                             1
                            else
                             null
                          end) over(partition by c.src_file_id) tot_trans,
                   row_number() over(partition by c.src_file_id order by null) rn
              from file_status fs
              left join comm c
                on c.src_file_id = fs.file_id
             where carr_cd = 'LIBM')
    where rn = 1;
    CARR_CD FILE_NAME            FILE_ID           TOT_REC   TOT_SUCC  TOT_TRANS
    LIBM    CM_LIBM.TXT          12345678                5          4          2
    LIBM    CM_LIBM.TXT          12345677               10          0          0Using RANK can potentially produce multiple rows to be returned though your data may prevent this. ROW_NUMBER will always prevent duplicates. The ordering of the analytical function is irrelevant in your query if you use ROW_NUMBER. You can remove the outermost query and inspect the data returned by the inner query;
    select fs.carr_cd,
           fs.file_name,
           fs.file_id,
           fs.tot_rec,
           fs.tot_succ,
           count(case
                    when c.status = 'T' then
                     1
                    else
                     null
                  end) over(partition by c.src_file_id) tot_trans,
           row_number() over(partition by c.src_file_id order by null) rn
    from file_status fs
    left join comm c
    on c.src_file_id = fs.file_id
    where carr_cd = 'LIBM';
    CARR_CD FILE_NAME            FILE_ID           TOT_REC   TOT_SUCC  TOT_TRANS         RN
    LIBM    CM_LIBM.TXT          12345678                5          4          2          1
    LIBM    CM_LIBM.TXT          12345678                5          4          2          2
    LIBM    CM_LIBM.TXT          12345678                5          4          2          3
    LIBM    CM_LIBM.TXT          12345678                5          4          2          4
    LIBM    CM_LIBM.TXT          12345677               10          0          0          1

  • Issue with recursive join and filter records

    I am having an issue with recursive join and filtering records for the following rules. The table, sample records, test script and rules are as below
    drop table PC_COVKEY_PD;
    create table PC_COVKEY_PD (
    PC_COVKEY varchar(50),
    COVERAGE_NUMBER varchar(3),
    SEQUENCE_ALPHA  varchar(3),
    TRANSACTION_TYPE varchar(3),
    COV_CHG_EFF_DATE date,
    TIMESTAMP_ENTERED timestamp
    delete from PC_COVKEY_PD;
    commit;
    Insert into PC_COVKEY_PD values ('10020335P8017MT0010012','001','001','02',to_date('01/FEB/2010','DD/MON/RRRR'),to_timestamp('02/JAN/2010 01:55:59.990216 AM','DD/MON/RRRR HH12:MI:SS.FF6 AM'));
    Insert into PC_COVKEY_PD values ('10020335P8017MT0050012','005','001','02',to_date('01/FEB/2010','DD/MON/RRRR'),to_timestamp('02/JAN/2010 01:56:00.268099 AM','DD/MON/RRRR HH12:MI:SS.FF6 AM'));
    Insert into PC_COVKEY_PD values ('10020335P8017MT0010032','001','003','03',to_date('14/JAN/2011','DD/MON/RRRR'),to_timestamp('14/JAN/2011 04:25:19.018217 PM','DD/MON/RRRR HH12:MI:SS.FF6 AM'));
    Insert into PC_COVKEY_PD values ('10020335P8017MT0010042','001','004','03',to_date('21/JAN/2011','DD/MON/RRRR'),to_timestamp('21/JAN/2011 04:00:31.719444 PM','DD/MON/RRRR HH12:MI:SS.FF6 AM'));
    Insert into PC_COVKEY_PD values ('10020335P8017MT0050022','005','002','03',to_date('21/JAN/2011','DD/MON/RRRR'),to_timestamp('21/JAN/2011 04:02:48.953594 PM','DD/MON/RRRR HH12:MI:SS.FF6 AM'));
    commit;
    --select * from PC_COVKEY_PD order by COV_CHG_EFF_DATE,TIMESTAMP_ENTERED;
    PC_COVKEY          COVERAGE_NUMBER     SEQUENCE_ALPHA     TRANSACTION_TYPE     COV_CHG_EFF_DATE     TIMESTAMP_ENTERED
    10020335P8017MT0010012          001     001                  02                          01/FEB/2010            02/JAN/2010 01:55:59.990216 AM
    10020335P8017MT0050012          005     001                  02                      01/FEB/2010            02/JAN/2010 01:56:00.268099 AM
    10020335P8017MT0010032          001     003                  03                      14/JAN/2011            14/JAN/2011 04:25:19.018217 PM
    10020335P8017MT0010042          001     004                  03                      21/JAN/2011            21/JAN/2011 04:00:31.719444 PM
    10020335P8017MT0050022          005     002                  03                      21/JAN/2011             21/JAN/2011 04:02:48.953594 PM
    */Rule;
    Every PC_COVKEY, query should recursively join and generate set of records depending on latest SEQUENCE_ALPHA for the coverage number at that point of time. For ex,
    for 10020335P8017MT0010042 (4 row) should generate 2 records
    1. 10020335P8017MT0010042001004 (PC_COVKEY || COVERAGE_NUMBER || latest SEQUENCE_ALPHA--004 for cover 001), SEQUENCE_ALPHA 001 for cover 001 is not the latest for 10020335P8017MT0010042.
    2. 10020335P8017MT0010042005001 (coverage number 005, and latest sequence alpha-001 for cover 005).
    SEQUENCE_ALPHA 002 for cover 005 is not the latest for 10020335P8017MT0010042 as it happened later stage.
    for 10020335P8017MT0050022 (5 row) should generate 2 records as
    1. 10020335P8017MT0050022001004 (PC_COVKEY || COVERAGE_NUMBER || latest SEQUENCE_ALPHA--004 for cover 001),
    2. 10020335P8017MT0010042005002 (coverage number 005, and latest sequence alpha-002 for cover 005)
    WITH SNAPSHOT_CVR_CTP as (
    SELECT pcd1.PC_COVKEY,
           pcd1.PC_COVKEY||pcd2.COVERAGE_NUMBER||pcd2.SEQUENCE_ALPHA as cov_key,
           pcd2.COVERAGE_NUMBER,
           pcd2.SEQUENCE_ALPHA,
           pcd2.COVERAGE_NUMBER||pcd2.SEQUENCE_ALPHA as CVRSEQ,
           max(pcd2.COVERAGE_NUMBER||pcd2.SEQUENCE_ALPHA) over (partition by pcd1.PC_COVKEY, pcd1.COVERAGE_NUMBER
           order by pcd2.COV_CHG_EFF_DATE, pcd2.TIMESTAMP_ENTERED) as MaxSeq,
           pcd2.COV_CHG_EFF_DATE,     
           pcd2.TIMESTAMP_ENTERED
    FROM
    PC_COVKEY_PD pcd1,
    PC_COVKEY_PD pcd2
    select * from SNAPSHOT_CVR_CTP SC
    WHERE sc.PC_COVKEY = '10020335P8017MT0010042'  -- 4 row
    --AND  COVERAGE_NUMBER||SC.MAXSEQ = COVERAGE_NUMBER||SEQUENCE_ALPHA
    ORDER BY TIMESTAMP_ENTERED
    PC_COVKEY     COV_KEY     COVERAGE_NUMBER     SEQUENCE_ALPHA     CVRSEQ          MAXSEQ     COV_CHG_EFF_DATE     TIMESTAMP_ENTERED
    10020335P8017MT0010042     10020335P8017MT0010042001001     001     001     001001     001001     01/FEB/2010     02/JAN/2010 01:55:59.990216 AM
    10020335P8017MT0010042     10020335P8017MT0010042005001     005     001     005001     005001     01/FEB/2010     02/JAN/2010 01:56:00.268099 AM
    10020335P8017MT0010042     10020335P8017MT0010042001003     001     003     001003     005001     14/JAN/2011     14/JAN/2011 04:25:19.018217 PM
    10020335P8017MT0010042     10020335P8017MT0010042001004     001     004     001004     005001     21/JAN/2011     21/JAN/2011 04:00:31.719444 PM
    10020335P8017MT0010042     10020335P8017MT0010042005002     005     002     005002     005002     21/JAN/2011     21/JAN/2011 04:02:48.953594 PM
    I am trying to filter row using MAXSEQ but at the moment MAXSEQ values are not coming as expected. I expect following value for COV_KEY combination
    COV_KEY                                         MAXSEQ
    10020335P8017MT0010042001001     001004
    10020335P8017MT0010042005001     005001 -- match
    10020335P8017MT0010042001003     001004
    10020335P8017MT0010042001004     001004 -- match
    10020335P8017MT0010042005002     005001Would appreciate if anyone can get MAxSEQ as expected.

    Something like..
    with dist_cov_numbers as
      select distinct coverage_number cov_number
      from PC_COVKEY_PD
    all_data as
      select pcd.*,d.cov_number new_coverage_number,
             max(decode(coverage_number,d.cov_number,sequence_alpha))
                  over( partition by d.cov_number
                        order by COV_CHG_EFF_DATE,TIMESTAMP_ENTERED
                                  ) max_seq
      from PC_COVKEY_PD pcd,dist_cov_numbers d
    select pc_covkey,pc_covkey||new_coverage_number||max_seq new_key,
           pc_covkey||coverage_number||sequence_alpha actual_key
    from all_data
    order by COV_CHG_EFF_DATE, TIMESTAMP_ENTERED;
    PC_COVKEY                   NEW_KEY                           ACTUAL_KEY                     
    10020335P8017MT0010012      10020335P8017MT0010012001001      10020335P8017MT0010012001001     
    10020335P8017MT0010012      10020335P8017MT0010012005         10020335P8017MT0010012001001     
    10020335P8017MT0050012      10020335P8017MT0050012001001      10020335P8017MT0050012005001     
    10020335P8017MT0050012      10020335P8017MT0050012005001      10020335P8017MT0050012005001     
    10020335P8017MT0010032      10020335P8017MT0010032001003      10020335P8017MT0010032001003     
    10020335P8017MT0010032      10020335P8017MT0010032005001      10020335P8017MT0010032001003     
    10020335P8017MT0010042      10020335P8017MT0010042005001      10020335P8017MT0010042001004     
    10020335P8017MT0010042      10020335P8017MT0010042001004      10020335P8017MT0010042001004     
    10020335P8017MT0050022      10020335P8017MT0050022005002      10020335P8017MT0050022005002     
    10020335P8017MT0050022      10020335P8017MT0050022001004      10020335P8017MT0050022005002 
    10 rows selected Edited by: jeneesh on Nov 22, 2012 10:54 AM

  • Outer join with where clause in the universe

    Hi,
    I have two tables such as:
    Patient Table (P)                          Territory Table (T)
    P. Alignment ID --------------------------   T.Alignment ID
    P. Patient ID                                    T. Region
    Two tables are joined on alignment ID, follow is how the data looks like
    When i run the query only on Patient Table  i get the following
    e.g.
    Select P.Patient ID, P.Alignment ID
    from Patient Table (P)
    Where P.Data_date=P.Latest data date
    ----Note that there is a Where clause here always & i get the following result
    P.Patient ID         P.Alignment ID      
        1                            1a
        2                             2a
        3                            3a
        4                            Null
        5                            Null
    Now when i join two tables on Alignment ID
    e.g.
    Select P.Patient ID, P.Alignment ID,T.Region
    from Patient Table (P)
    LEFT OUTER  JOIN Territory Table (T)
    ON P. Alignment ID =  T.Alignment ID
    Where P.Data_date=P.Latest data date
    AND T.Data_date=T.Latest data date
    Following is the result:
    P.Patient ID         P.Alignment ID      
        1                            1a
        2                            2a
        3                            3a
    Even with the left outer join it is not brining in the Null values , it seems that because of the WHERE clause the LEFT OUTER is working as a INNER join.
    How can i get the Null rows with my join to the territory table ?
    Please Advise,
    Thanks,
    Sheikh

    its not letting me atatched the excel extract but the data is simple as i shown above e.g.
    Patient Table (P)                          Territory Table (T)
    P. Alignment ID --------------------------   T.Alignment ID
    P. Patient ID                                    T. Region
    Two tables are joined on alignment ID, follow is how the data looks like
    When i run the query only on Patient Table  i get the following
    e.g.
    Select P.Patient ID, P.Alignment ID
    from Patient Table (P)
    Where P.Data_date='01-OCT-2014'
    ----Note that there is a Where clause here always & i get the following result
    P.Patient ID         P.Alignment ID      
        1                            1a
        2                             2a
        3                            3a
        4                            Null
        5                            Null
    Now when i join two tables on Alignment ID
    e.g.
    Select P.Patient ID, P.Alignment ID,T.Region
    from Patient Table (P)
    LEFT OUTER  JOIN Territory Table (T)
    ON P. Alignment ID =  T.Alignment ID
    Where P.Data_date='01-OCT-2014'
    AND T.Data_date='01-OCT-2014'
    Following is the result:
    P.Patient ID         P.Alignment ID      
        1                            1a
        2                            2a
        3                            3a
    Now the whole issue is that the condition in the WHERE clause is making it act like a inner join and iw ant the NULL rows to appear
    Sheikh

  • Are inner join and equijoin are same....?

    are inner join and equijoin are same....?

    WhiteHat wrote:
    interesting it says that - an equi join is a type of inner join but you can't really say they are the same thing.Simply said it it like this:
    Equi join means compare two tables where a value is in each table using an equal sign.
    An inner join means: We use the INNER JOIN keyword and have a join condition between the two tables.
    example1
    select *
    from emp
    inner join dept on emp.dept_no = dept.dept_no;This example is an inner join and also an equi join.
    example2
    select *
    from emp
    inner join dept on emp.dept_no >= dept.dept_no;This example is an inner join which is NOT an equi join.
    How to interpret the outcome is a different story (in this case it doesn't make much sense). However the syntax is correct and it is an inner join. But since it doesn't use the equal operator it is an non-equi join.

  • Join, and filter...

    When doing a join, and filtering, I want the filter to be applied first. For example
    if the callDisp file for the given date has 18 rows, and the treeProject has 47 records
    SELECT COUNT(*) from treeProject, callDisp
    Where
    treeProject.projectcode = callDisp.projectcode(+) and
    treeProject.childcode = callDisp.disp(+) and
    treeProject.projectcode = 'project' and
    calldisp.dispDateTime >= to_date( '01-14-2003', 'MM-DD-YYYY' );
    COUNT(*)
    17
    The idea is to list all of the rows meeting the critera in the treeproject, by doing the outer join on the callDisp table. Which works fine if the datetime part of the query is not entered. I tried modifing the query to add the nulls:
    SELECT COUNT(*) from treeProject, callDisp
    Where
    treeProject.projectcode = callDisp.projectcode(+) and
    treeProject.childcode = callDisp.disp(+) and
    treeProject.projectcode = 'project' and
    calldisp.dispDateTime >= to_date( '01-14-2003', 'MM-DD-YYYY' ) or
    calldisp.dispDateTime is null
    COUNT(*)
    18
    or even:
    SELECT COUNT(*) from treeProject, callDisp
    Where
    treeProject.projectcode = callDisp.projectcode(+) and
    treeProject.childcode = callDisp.disp(+Long postings are being truncated to ~1 kB at this time.

    or even:
    SELECT COUNT(*) from treeProject, callDisp
    Where
    treeProject.projectcode = callDisp.projectcode(+) and
    treeProject.childcode = callDisp.disp(+) and
    treeProject.projectcode = 'project' and
    calldisp.dispDateTime >= to_date( '01-14-2003', 'MM-DD-YYYY' ) or
    nvl(calldisp.dispDateTime,to_date( '01-14-2003', 'MM-DD-YYYY' ) ) = to_date( '01-14-2003', 'MM-DD-YYYY' )
    COUNT(*)
    18
    But without getting the desired results. I want the filter to occur first, and the join to occur last.
    Thanks
    Rich

Maybe you are looking for