Foreign key check - possible where clause

I want to create a foreign key referential constraint, but I want to do this only for certain data.

example 2 tables. With 5 rows T1, t1 is to reference col1 in t1, but where the only col2 = "a". If I have all the data of reference I get an error creating the audit as t1.col1 is not unique for all data and is not a PK.
create table t1
   (col1 varchar(1),
   col2 varchar(1))
   
   create table t2
   (col1 varchar(1),
   col3 varchar(1))
   
   insert into t1 values ('a','a');
   
   insert into t1 values ('b','a');
   
   insert into t1 values ('c','a');
   
   insert into t1 values ('d','b');
   
   insert into t1 values ('d','b');

commit;

alter table t2
  add constraint FK_t1_col1 foreign key (col1)
  references t2(col1);

ORA-02270: no matching unique or primary key for this column-list
This is an example of a small subset of a much larger table where col1 is not the PK and I can't create a unique index on it as his unique not on its own.

I could create a materialized view but would rather not if possible. Y at - it solution or method on t1 to create the repository control with a where clause clause in order to do something like the following pseudocode
alter table t2
  add constraint FK_t1_col1 foreign key (col1)
  references t2(col1)   
    where col2 = 'a' ;

961469 wrote:
I want to create a foreign key referential constraint, but I want to do this only for certain data.

example 2 tables. With 5 rows T1, t1 is to reference col1 in t1, but where the only col2 = "a". If I have all the data of reference I get an error creating the audit as t1.col1 is not unique for all data and is not a PK.

You don't have to have a primary key as a reference point, it must be unique, and it may be a virtual column. If you are running 11g is easy:

drop table t2;
drop table t1;

create table t1 (
     code_type     varchar2(10)     not null,
     code_number     number(10)     not null,
     a_code          generated always as
                    (case code_type when 'A' then code_number else null end)
);

alter table t1 add constraint t1_uka unique (a_code);

create table t2(
     id1     number not null references t1(a_code)
);

insert into t1 (code_type, code_number) values('A',1);

-- next row is not a duplicate

insert into t1 (code_type, code_number) values('B',1);

insert into t1 (code_type, code_number) values('B',2);

-- next row succeeds

insert into t2 values(1);

-- next row fails

insert into t2 values(2);

commit;

Concerning
Jonathan Lewis

Tags: Database

Similar Questions

  • Foreign key, check force

    Hello

    This is the structure of two two table.

    Untitled.png

    DDL:

    CREATE TABLE TEST_PARENT
      (
        PARENT_KEY NUMBER (22),
        PARENT_ID NUMBER (22),
        PARENT_NAME VARCHAR2 (255 CHAR),
        EFFECTIVE_START_DATE DATE DEFAULT sysdate NOT NULL ,
        EFFECTIVE_END_DATE   DATE
      ) ;
    ALTER TABLE TEST_PARENT ADD CONSTRAINT PK_TEST_PARENT PRIMARY KEY ( PARENT_KEY ) ;
    
    
    CREATE TABLE TEST_CHANNEL
      (
    
    
        CHANNEL_KEY NUMBER (22),
        CHANNEL_ID NUMBER (22),
        CHANNEL_NAME VARCHAR2 (255 CHAR),
        EFFECTIVE_START_DATE DATE DEFAULT sysdate NOT NULL ,
        EFFECTIVE_END_DATE   DATE 
      ) ;
    ALTER TABLE TEST_CHANNEL ADD CONSTRAINT PK_TEST_CHANNEL PRIMARY KEY ( CHANNEL_KEY ) ;
    

    Logic:

    Parent_id is always fixed to a Parent. But a Parent can have different attributes (parent_name here). Where the attributes are changing it will end the bu previous records put a value to effective_end_date and it will create a new line. New line will have the PARENT_KEY new PARENT_NAME with new effective_start_date and null in effective_end_date.

    Same logic applies to the CHILD table as well.

    What is the best way to put a reference to the type of the foreign key in the CHILD table that in case, will ensure that a child cannot exist without a parent now. I can't take PARENT_KEY as a foreign key to the same parent can change the PARENT_KEY and a child must always point to the parent ASSET (EFFECTIVE_END_DATE as null) folder.

    Thanks in advance.

    I would enrich your datamodel by tables of the object/version as:

    CREATE TABLE TEST_PARENT_OT
    (
    NUMBER OF PARENT_KEY (22) NOT NULL
    ) ;

    ALTER TABLE TEST_PARENT_OT ADD CONSTRAINT PK_TEST_PARENT_OT PRIMARY KEY (PARENT_KEY);

    CREATE TABLE TEST_PARENT_VT
    (
    NUMBER OF PARENT_KEY (22) NOT NULL,
    NUMBER of VERSION_ID (22) not null,
    PARENT_NAME VARCHAR2 (255 CHAR),
    EFFECTIVE_START_DATE DATE default sysdate NOT NULL,
    DATE OF EFFECTIVE_END_DATE
    ) ;

    ALTER TABLE TEST_PARENT_VT ADD CONSTRAINT PK_TEST_PARENT_VT PRIMARY KEY (PARENT_KEY, VERSION_ID);
    ALTER TABLE TEST_PARENT_VT add CONSTRAINT FK_PARENT_VT_PARENT_OT foreign key (parent_key) refers to test_parent_ot (parent_key);

    CREATE TABLE TEST_CHANNEL_OT
    (
    NUMBER OF CHANNEL_KEY (22) NOT NULL
    ) ;

    ALTER TABLE TEST_CHANNEL_OT ADD CONSTRAINT PK_TEST_CHANNEL_OT PRIMARY KEY (CHANNEL_KEY);

    CREATE TABLE TEST_CHANNEL_VT
    (
    NUMBER OF CHANNEL_KEY (22) NOT NULL,
    NUMBER OF VERSION_ID (22) NOT NULL,
    PARENT_KEY NUMBER (22) NOT NULL,
    CHANNEL_NAME VARCHAR2 (255 CHAR),
    EFFECTIVE_START_DATE DATE default sysdate NOT NULL,
    DATE OF EFFECTIVE_END_DATE
    ) ;

    ALTER TABLE TEST_CHANNEL_VT ADD CONSTRAINT PK_TEST_CHANNEL_VT PRIMARY KEY (CHANNEL_KEY, VERSION_ID);
    ALTER TABLE TEST_CHANNEL_VT add CONSTRAINT FK_CHANNEL_VT_CHANNEL_OT FOREIGN KEY (channel_key) REFERENCES TEST_CHANNEL_OT (channel_key);
    ALTER TABLE TEST_CHANNEL_VT add CONSTRAINT FK_CHANNEL_VT_PARENT_OT FOREIGN KEY (PARENT_key) REFERENCES test_parent_ot (parrent_key);

    Using this you will not have to reallocate your child of the lines when a new version of parent is created and you will be able to have the independent channel versions of the parent versions (so no need to change all the children when the parents ends).

    the construction of views of parents and the channels which only show active lines.

    The problem you may have is to be sure to have for each point in time an active version and so I would not implement of an effective_end date, but inherit the effective end of the effective next to (which is a little more work but you will help gapelessness if necessary)

    HTH

  • where clause to query the hierarchy in the tree Apex area does not

    Hi all

    I am building a tree Menu in Apex 5.0.3 (Oracle 11 g XE), when using when the clause, it does show all the data, but without him, showing all the data.

    I'm trying to populate Tree Menu with data specific to a user successfully logged on.

    (A) table created as HR2. TREE_MENU

    menu_name varchar2 (50).

    number of menu_parent

    number of menu_child

    menu_id varchar2 (12),

    menu_path varchar2 (100),

    number of user_no

    (B) SQL statement for the tree in the Apex region

    Select case when connect_by_isleaf = 1 then 0

    When level = 1 then 1

    else                           -1

    end the status,

    level,

    'Menu_name' as the title,

    NULL as an icon,

    "MENU_CHILD" as a value.

    NULL as ToolTip,

    NULL as link

    to HR2. "" TREE_MENU ".

    -WHERE USER_NO =: P_USERNO

    Start with 'MENU_CHILD' is null

    connect prior "MENU_PARENT" = "MENU_CHILD."

    brothers and sisters of order by 'MENU_ID '.

    Note: also used static value where clause but is not workd.

    that the mistake of me or something else? When using the wizard, she asks (possibly) where clause, this means that when the clause can be used in the SQL statement.

    Help, please.

    Kind regards.

    If you want to prune your tree to show only the elements of the No. 7 usermenu, copy the following code helps you

    select case when connect_by_isleaf = 1 then 0
                when level = 1             then 1
                else                           -1
           end as status,
           level,
           "MENU_NAME" as title,
           null as icon,
           "MENU_CHILD" as value,
           null as tooltip,
           null as link
    from HR2."TREE_MENU"
    start with "MENU_CHILD" is null
    connect by
        prior "MENU_PARENT" = "MENU_CHILD"
        and "USER_NO" = 7
    order siblings by "MENU_ID"
    

    Concerning

    Mahmoud

  • How to make a primary foreign key?

    I'm working on my data model and I can't understand how a foreign key to be a primary foreign key... I'll make a primary foreign key for this specific table 2...
    I tried to do the foreign key checked as the primary_UID... but this isn't the solution... I want to show in the relational model indicated as "PF" or the primary foreign key

    Anyone know? Thanks in advance

    Hi Delos,

    What version of SQL Developer Data Modeler do you use?
    For me, it works in 3.1.1.703 and 3.1.2.704.
    Can you provide more details.
    For the logic model you can use the Unique identifier dialog box and add links to the list of used objects.

    Philippe

  • How to check where the table field has been used as a foreign key in the database

    Hi I have a field in my table Office I had office_code field, this field has been used in the tables of diffirent as foreign key is a sql I can wirte to see all the tables that have used this field as a foreign key

    Edited by: adf009 09/05/2013 10:37

    Edited by: adf009 09/05/2013 10:38

    Check this box

    SELECT * FROM user_constraints WHERE table_name='EMP' and CONSTRAINT_TYPE='R';
    

    Type = 'R' means referential integrity constraint type.

  • Order columns (which make up the primary key constraint) matter in where clause of DML query for use of indexing mechanism to operate.

    Version of DB: database Oracle 11 g Enterprise Edition Release 11.2.0.3.0 - 64 bit Production


    I have a table my_table as below:
    create table my_table
    (
    my_code varchar2 (6).
    my_id varchar2 (24).
    forced pk_1 primary key (my_code, my_id)
    );


    Primary_key here's a composite key that contains columns 1 (my_code) and 2 (my_id).
    Is there that a difference in the way below queries is executed in terms of performance (use of indexing in the extraction).

    (a) select * from my_table where my_code = '123' and my_id = "456";
    (b) select * from my_table where my_id = '456' and my_code = '123';


    The understanding I have the order of the column in the where clause should be identical to the sequence in
    What primary key draws for indexing to be used by oracle in oracle other DML queries ignores indexing
    However when I used explain plain both show the same query cost with single scan with index rowid.
    so I don't know if I'm wrong in the concept that I have. Kindly help.

    Thanks in advance,
    Gerard

    Your question is answered in the Performance Tuning Guide

    Using indexes and clusters

    14.1.4 choosing composite indexes

    A composite index contains several key columns. Composite indexes can provide additional benefits compared to the index to single column:

    • Improved selectivity

      Sometimes the two or more columns or expressions, each with a low selectivity can be combined to form a composite with a high selectivity.

    • Reduced IO

      If all columns selected by a query are a composite index, then Oracle may return these values in the index without access to the table.

    A SQL statement can use a path on a composite index if the statement contains constructions that use a main part of the index.

    Note:

    This is no longer the case with the skip index scans. See "Index Skip Scans".

    A main part of an index is a set of one or more columns that have been specified first and consecutively in the list of columns in the CREATE INDEX statement that created the index.

  • foreign key 'generate' strange behavior check box, any idea?

    Summary: in the properties of the table, the foreign keys, the box generate behaves badly, and I don't understand why or how I got there.

    Oracle Data Modeler 4.0.2.840 8.1 X 64 Windows, jdk1.7.0_55

    the behavior is:

    (1) add the foreign key (two different more to see strange behavior)

    (2) uncheck 'generate' on a foreign key

    (3) apply, Ok

    (4) ask 'Preview DDL', a foreign key constraint is generated, SO FAR SO GOOD, I'm happy

    5-now click on the button 'generate the DDL' for any design = > * * TWO foreign keys are generated?

    (6) even more strange: sometimes the 'generate' check itself after step 5, most of the time is not

    (7) at the beginning this has occurred for a couple of foreign key 'uncheckees', now it almost always happens.

    The relational model was built by importing the SQL scripts already exist (try to migrate the Data Modeler). No too complex ~ 115 tables, 12 times.

    I think it's a bug, but I can't find any reference on the web, maybe I do something wrong?

    Hi Michel,.

    The generation is different depending on whether or not the relevant storage design is open.

    If the design of the storage is not open, the option "Generate DDL" on the foreign key is taken into account (for an overview of the DDL or full generation of DDL).  For an entire generation of DDL, the foreign key will initially not selected phase in the generation of the DDL if Options the option "Generate DDL" on the foreign key has been disabled.  (This change in the phase of the generation of DDL Options will also cause the option "Generate DDL" on the foreign key update.)

    If the design of the storage is open, the option 'generate DDL"on the foreign key has no effect (in a Preview of DDL or full DDL generation).

    Also in a generation full of DDL, an object will be initially marked as not selected if it has been disabled in the previous generation of DDL.

    I hope that this helps to explain the behavior that you find.

    David

  • by the way check box values in the WHERE clause

    Hello

    I created a data block - 'CONTACT' (block of data in database)

    and has an element of database - 'Code', 'Descr '.

    The number of records displayed has the value 5.

    When enabled - value 'Y '.

    Value when disabled - n

    Box mapping of other values - "unchecked."


    I write the code inside "WHEN the BUTTON PRESS. My main goal is to return the number of records from

    According to several conditions and one among them is the CODE which can be single or multiple based on the checked checkbox.

    The requirement is when I check one or more boxes, I should pass the "Code" element values in the WHERE clause.

    I tried to use the simple loop but things havmt worked as shown below.

    The next_record refers to the COCHEE BOX as well, and thus return all the eventhough lines if it is not checked.

    ----------------------------------------------------------------------------

    -LOOP

    IF: contact.cb = 'Y' THEN

    LOOP

    IF p_where is null then

    p_where: =: contact.code;

    on the other

    p_where: = p_where | «, » || : contact.code;

    end if;

    When the output: system.last_record = "TRUE";

    next_record;

    END LOOP;

    end if;

    -END LOOP;

    MESSAGE ("p_where :'|| p_where);

    MESSAGE (' ');

    END;


    ------------------------------------

    And even if I write the LOOP before the first CASE, it returns me the current value and move to the last record.

    Please suggest

    Try something like this:

    FIRST_RECORD;
    
    LOOP
    
      IF :contact.cb = 'Y' THEN
        IF p_where is null then
           p_where := :contact.code;
         else
           p_where := p_where ||','||:contact.code;
         end if;
       END IF;
      exit when :system.last_record = 'TRUE';
      next_record;
    END LOOP;
    
    -- END LOOP;
    MESSAGE ( 'p_where :'||p_where);
    MESSAGE (' ');
    
    END;
    
  • How to set the condition of rule to check the Primary Key, Foreign Key and Unique

    I use Oracle 10.2
    Could someone tell me please how to set the rule condition to check the primary key, foreign key constraint of uniqueness?

    Hello

    Primary key, unique constraints and foreign key are better applied using the native functionality of database constraint. If you like the rules to check if a key exists at the time of the evaluation, you can use a function defined by the user in a rule condition and this function can ask to turn the table keys.

    Hope this helps,
    -Aravind.

  • pl/sql is it possible to put the cursor in where clause?

    Hello

    I have this stored proc that works very well when it is passed a single ID... now he must pass a list of IDS as in
    function (cursor (select id from table))...


    its definition is like this:
    RETURN ACTIV_PKG.tADR_ACTIV PIPELINED IS function ADR_ACTIV (pi_NO_SEQ IN sys_refcursor)
    CURSOR c1 (p_NOSEQ IN sys_refcursor) IS
    WITH Lateststate AS
    (SELECT RESUM_ETA.NO_SEQ_CLE_PRIM NO_SEQ_ADR,
    ADR.NO_SEQ,
    RESUM_ETA. COD_ETA
    OF RESUM_ETA
    JOIN INTERNAL ADR
    ON ADR.NO_SEQ_ADR = RESUM_ETA.NO_SEQ_CLE_PRIM
    WHERE RESUM_ETA. COD_TBL = "ADR1".

    and IN ADR.NO_SEQ (p_NOSEQODS)


    )...

    You see that 'and ADR.NO_SEQ IN (p_NOSEQODS)' lines using only those on the list filters...

    the idea is to use the cursor c1 like this:
    BEGIN
    FOR rec1 IN c1 (pi_NO_SEQ)
    LOOP
    ...

    Except that I get an error with (p_NOSEQODS) because it is not supported...

    y at - there a trick to this?

    Should I use table instead of cursor in where clause IN (...)?


    I have not in a list of IDS and put it in where clause of my cursor c1... How to get there?

    Thanks for the advice/links

    See you soon!

    the idea is to use the cursor c1 like this:
    FOR rec1 IN c1 (pi_NO_SEQ)

    Don't know if it's really less awkward that solution regexp, but we here are:

       cur   sys_refcursor;
    
       cursor c2 (cur sys_refcursor)
       is
          select   *
            from   emp
           where   empno in (select   trim (t.column_value.extract ('//text()'))
                               from   table (xmlsequence (cur)) t);
    begin
       open cur for
          select   7788 from dual
          union all
          select   7900 empno from dual;
    
       for c in c2 (cur)
       loop
          dbms_output.put_line (c.ename);
       end loop;
    end;
    /
    SCOTT
    JAMES
    PL/SQL procedure successfully completed.
    
  • Cannot run a «BUSINESS...» WHEN ' with a date in a WHERE CLAUSE condition

    Hello

    I need to check for a condition and date according to the date, he would check a set of host names or the other game... so I thought I could write something like this in the WHERE clause:

    AND HOST_NAME IN

    (

    CASE

    WHEN TO_DATE (: StopDate, 'MON-DD-YYYY') > = TO_DATE ('22 - DEC - 2015 "," DD-MON-YYYY ') THEN

    ('SERVERNAMEA', 'SERVERNAMEB', 'SERVERNAMEC') ON THE OTHER

    ("SERVERNAME1", "NAMESERVER2", "SERVERNAME3")

    END

    )

    I get the following:

    ORA-00907: lack of right parenthesis

    00907 00000 - "lack the right parenthesis.

    But there is no missing parentheses!

    If I take the case... when... end, and run the host_name in ('SERVERNAMEA', 'SERVERNAMEB', 'SERVERNAMEC') (separately, they run fine)...

    I also tried:

    AND

    (

    CASE

    WHEN TO_DATE (: StopDate, 'MON-DD-YYYY') > = TO_DATE ('22 - DEC - 2015 "," DD-MON-YYYY ') THEN

    HOST_NAME IN ('SERVERNAMEA', 'SERVERNAMEB', 'SERVERNAMEC') ELSE

    HOST_NAME IN ('SERVERNAME1","NAMESERVER2","SERVERNAME3")

    END

    )

    the error I get is:

    ORA-00905: lack of keyword

    00905 00000 - 'lack the key word'

    What keyword miss me?

    Post edited by: c75d2e42-06a0-4eb1-a576-5652edcbfbe8

    Hello

    c75d2e42-06a0-4eb1-A576-5652edcbfbe8 wrote:

    It was a typo when transferred to the Oracle forum... the version of Oracle is: PL/SQL version 10.2.0.3.0 (10 G)

    I also used IF the statement and that has not worked (in error "missing parenthesis") which I'm sure is a matter of "syntax"... I did not know that the CASE statement returns the value single only, so it's probably the problem.  Is it possible to re - write this?

    ...

    IF only works in PL/SQL.  It does not in SQL, even if that SQL is embedded in PL/SQL.

    There are many ways to re - write the condition.  And here's one:

    AND ((host_name IN ('SERVERNAMEA', 'SERVERNAMEB', 'SERVERNAMEC')

    AND TO_DATE (: StopDate, "MON-DD-YYYY") > = TO_DATE ('22-DEC-2015', "MON-DD-YYYY")

    )

    OR (host_name IN ('servername1","Nameserver2","SERVERNAME3")

    AND TO_DATE (: StopDate, "MON-DD-YYYY")<  to_date="" ('dec-22-2015', ="">

    )

    )

    If: StopDate can be NULL, it must be a bit more complicated.

    You can also use nested, such as CASE expressions

    AND THE CASE

    WHEN TO_DATE (: StopDate, "MON-DD-YYYY") > = TO_DATE ('22-DEC-2015', "MON-DD-YYYY")

    WHILE CASE

    WHEN host_name IN ('SERVERNAMEA', 'SERVERNAMEB', 'SERVERNAMEC')

    AND THEN 'OK '.

    END

    OTHER CASES

    WHEN host_name IN ('servername1","Nameserver2","SERVERNAME3")

    AND THEN 'OK '.

    END

    END = 'OK '.

    I wonder if this in your application is the best way, however.  If SERVERNAMEA was put into service on December 22, maybe that that fact should be recorded in a table.  If you have a table with 1 row per server, you can consider adding 2 columns DATE to show when the server was first and last used.  Then, rather than use a WHERE clause to test servers appropriate, you could do an inner join.

  • Query where clause of different table without data

    Hello

    Oracle 11g.

    I have a 'Points' table that stores information point.
    In carts, users can record information on these points.
    Then, the user can some carts he wants to apply to display data in a report.

    Here is a minimal example (I hope I didn't too many mistakes):
    create table points (
         pt_id integer,
         pt_type varchar2(1),
         pt_accl varchar2(15),
         pt_class varchar2(10),
         pt_status varchar2(1),
         constraint pk_pt_id primary key(pt_id),
         constraint ck_pt_type check(pt_type in ('B','P', 'S', 'T')),
         constraint ck_pt_status check(pt_status in ('A','E'))
    );
    
    create table carts(
         cart_id integer,
         cart_name varchar2(30),
         cart_current varchar2(1),
         constraint pk_cart_id primary key(cart_id),
         constraint ck_cart_current check(cart_current in ('Y','N')) 
    );
    
    create table user_selected_types(
         ust_id integer,
         ust_cart_id integer,
         ust_type varchar2(1),
         constraint pk_ust_id primary key(ust_id),
         constraint fk_ust_cart_id foreign key(ust_cart_id) references carts(cart_id)
    );
    
    create table user_selected_accls(
         usa_id integer,
         usa_cart_id integer,
         usa_accl varchar2(15),
         constraint pk_usa_id primary key(usa_id),
         constraint fk_usa_cart_id foreign key(usa_cart_id) references carts(cart_id)
    );
    
    create table user_selected_classes(
         usc_id integer,
         usc_cart_id integer,
         usc_class varchar2(10),
         constraint pk_usc_id primary key(usc_id),
         constraint fk_usc_cart_id foreign key(usc_cart_id) references carts(cart_id)
    );
    
    create table user_selected_status(
         uss_id integer,
         uss_cart_id integer,
         uss_status varchar2(1),
         constraint pk_uss_id primary key(uss_id),
         constraint fk_uss_cart_id foreign key(uss_cart_id) references carts(cart_id)
    );
    
    insert into carts values (1, 'cart_1', 'N');
    insert into carts values (2, 'cart_2', 'Y');
    insert into carts values (3, 'cart_3', 'Y');
    
    insert into points values (1, 'B', 'AAA', 'AAKCM', 'A');
    insert into points values (2, 'B', 'BIONH1', 'AAKCM', 'A');
    insert into points values (3, 'B', 'BIONH1', 'AAKCM', 'E');
    insert into points values (4, 'B', 'CTF1', 'RF45Q33', 'E');
    insert into points values (5, 'T', 'L4C', 'H4V1', 'A');
    insert into points values (6, 'T', 'L4C', 'H4V1', 'E');
    insert into points values (7, 'S', 'BIONH1', 'RX4', 'A');
    insert into points values (8, 'S', 'L4D', 'L2585', 'A');
    insert into points values (9, 'S', 'L4D', 'L2585', 'E');
    insert into points values (10, 'S', 'CTF1', 'CCMBQX', 'A');
    insert into points values (11, 'S', 'CTF1', 'CCMBQX', 'E');
    insert into points values (12, 'S', 'CTF2', 'CCMBQX', 'A');
    insert into points values (13, 'S', 'CTF2', 'CCMBQX', 'E');
    insert into points values (14, 'P', 'H4', 'L44W', 'A');
    insert into points values (15, 'P', 'H4', 'L44W', 'E');
    insert into points values (16, 'P', null, 'RK', 'E');
    
    insert into user_selected_types values (1, 1, 'B');
    insert into user_selected_types values (2, 1, 'S');
    insert into user_selected_types values (3, 3, 'T'); 
    
    insert into user_selected_accls values (1, 1, 'BIONH1');
    insert into user_selected_accls values (2, 2, 'CTF1');
    insert into user_selected_accls values (3, 2, 'CTF2');
    insert into user_selected_accls values (4, 3, 'L4C');
    
    insert into user_selected_classes values (1, 1, 'AAKCM');
    
    insert into user_selected_status values (1, 3, 'A');
    If a user may for example have the following carts (according to the example above):
    cart_1
    Types : 'B', 'S'
    Accls : 'BIONH1'
    Classes : 'AAKCM'
    Status : [All]
    
    cart_2
    Types : [All]
    Accls : 'CTF1', 'CTF2'
    Classes : [All]
    Status : [All]
    
    cart_3
    Types : 'T'
    Accls : 'L4C'
    Classes : [All]
    Status : 'A'
    When no value is selected for an item, it must return all values.

    For now, I have the following query:
    with t as (select cart_id d from carts where cart_current = 'Y')
    select
         *
    from
         points
    where
         ...
         and (
              pt_type in (select ust_type from user_selected_types where ust_cart_id in (select d from T))
              or not exists (select 1 from user_selected_types where ust_cart_id in (select d from T)))
         and (
              nvl(pt_accl, '' - (null)'') in (select nvl(usa_accl, '' - (null)'') from user_selected_accls where usa_cart_id in (select d from T))
              or not exists (select 1 from user_selected_accls where usa_cart_id in (select d from T)))
         and (
              pt_class in (select usc_class from user_selected_classes where usc_cart_id in (select d from t))
              or not exists (select 1 from user_selected_classes where usc_cart_id in (select d from T)))
         and (
              pt_status in (select uss_status from user_selected_status where uss_cart_id in (select d from T))
              or not exists (select 1 from user_selected_status where uss_cart_id in (select d from T)))
    It works, but the data or mixed...
    If the user apply cart_2 and cart_3, I don't want to for example points to accl "L4C" with status "E", forthcoming.
    I just want to return the union all selected each carts.

    Of course I can loop over Cart ID, PL_SQL, and build the query dynamically, as:
    for cur_c in (select cart_id d from carts where cart_current = 'Y') loop
         l_query := l_query || 'select ... from ... where ...' || ' union all ';
    end loop;
    l_query := substr(l_query,1,length(l_query)-11);
    But imagine the user ask 500 wagons..., I've reached the limit of varchar2.
    I can't use a CLOB that I use Oracle APEX to view the report, and he expects the query a varchar2.

    I don't want to use a temporary table, as it is too slow for the application (I've tested).

    You have a solution?

    Thank you.

    Yann.

    Thanks for create/insert statements - makes it much easier to help :D

    Here's one way:

    SQL> select
      2  c.cart_id,
      3  p.pt_id,
      4  p.pt_type,
      5  p.pt_accl,
      6  p.pt_class,
      7  p.pt_status
      8  from carts c
      9  cross join points p
     10  where c.cart_current = 'Y'
     11  and ( not exists(select null from user_selected_types ust where ust.ust_cart_id = c.cart_id)
     12     or p.pt_type in (select ust.ust_type from user_selected_types ust where ust.ust_cart_id = c.cart_id)
     13      )
     14  and ( not exists(select null from user_selected_accls usa where usa.usa_cart_id = c.cart_id)
     15     or p.pt_accl in (select usa.usa_accl from user_selected_accls usa where usa.usa_cart_id = c.cart_id)
     16      )
     17  and ( not exists(select null from user_selected_classes usc where usc.usc_cart_id = c.cart_id)
     18     or p.pt_class in (select usc.usc_class from user_selected_classes usc where usc.usc_cart_id = c.cart_id)
     19      )
     20  and ( not exists(select null from user_selected_status uss where uss.uss_cart_id = c.cart_id)
     21     or p.pt_status in (select uss.uss_status from user_selected_status uss where uss.uss_cart_id = c.cart_id)
     22      )
     23  order by
     24  c.cart_id,
     25  p.pt_id
     26  ;
    
       CART_ID      PT_ID P PT_ACCL         PT_CLASS   P
    ---------- ---------- - --------------- ---------- -
             2          4 B CTF1            RF45Q33    E
             2         10 S CTF1            CCMBQX     A
             2         11 S CTF1            CCMBQX     E
             2         12 S CTF2            CCMBQX     A
             2         13 S CTF2            CCMBQX     E
             3          5 T L4C             H4V1       A
    
    6 rows selected.
    

    The cross join creates all the possible combinations of carriage/point. Then they are checked for 4 columns according to your rules. I think that the result is correct, if I read your question right?

    If it's the most effective depends a lot on your actual data. Are the usual cases each cart sets a very small subset of points, or each cart will usually define a substantial part of the points. Carts of how are your tables? How many tables of user_selected_? How is the distribution? How many points? Indexes are available?

    If the data are such that it can "pay" to build all of the possible production and "weed" down, then the foregoing can be very effective. If the data is such that the result is usually very small subset then the effectiveness may depend on the index are available.

    Test and see if it works for you ;-)
    If it takes hours, so if please give some information on the quantity and distribution of the data and the expected quantity and size carts etc. Then we could think in a different way...

  • correct handling of foreign keys in unique constraints for operations ON DELETE SET NULL

    During my troubleshooting at a client site, I came across an interesting setup where I would like to ask your opinion.


    Consider two tables ADTB and TBLB.

    ADTB:

    INT COLA1

    COLA2 INT

    TBLB:

    COLB1 INT

    COLA2 is COLB1 as a foreign key ON DELETE SET NULL value.

    COLA1 and COLA2 are combined into a UNIQUE for the BATTERY constraint.

    I have two records of TBLB:

    (1)

    (2)

    and two DRUM recordings:

    (1, 1)

    (2, 2)

    so far, all the constraints are valid.

    During my research, I learned that I can not put COLA2 null in ADTB for two lines at the same time:

    TBLA UPDATE set COLA2 = NULL where COLA1 = 1;

    -> OK

    TBLA UPDATE set COLA2 = NULL where COLA1 = 2;

    -> VIOLATED UNIQUE CONSTRAINT

    Unfortunately, it's something my application needs, anyway. In order to get this resolved, but I try to understand, what would happen if I:

    REMOVE THE TBLB;

    ?

    It should set COLA2 in ADTB "Null" on the two lines, which is not allowed due to the UNIQUE CONSTRAINT.

    Can someone shed light on this issue? Thank you.


    Yours,

    Ronny

    Unfortunately, as you say, you can't not NULL values in such a unique constraint.  It would be the same as if you had a composite primary key and try to allow one of the columns will be null in several rows with the same value in the other column.  NULL is treated as an "unknown" value, it is possible that it could be the same value (it may or may not be, but Oracle does not know), so it must assume that it might be and that's why treat it as if there is the potential for a duplicate... so it's not unique.

    In short, do not allow null values in your unique constraints.

    The default is in the drawing, not in the way that Oracle is the treatment.  Fix the design if you do not have NULL values.

    In terms of relational database design, it seems that you are trying to transform the 1:M relations M:M relations, and which requires an intermediate table if you have M:1 and 1:M between 3 tables instead.

  • Using decode in where clause

    Hello

    I need to use decode condition in where clause in such a way that if the respective column is null then consider the corresponding column

    for example

    Fee_dateFee_refund_date
    10 OCTOBER 05
    12 NOVEMBER 05
    11 JANUARY 06
    16 FEBRUARY 06

    I have a request in place as below where p_fee_flag will be passed as either FEES or set to null, I check another condition as if p_fee_flag is null then fee_date must be set to null when comparing fee_refund_date between TRUNC (BKT. ACT_START_DATE) AND TRUNC (BKT. ACT_END_DATE

    SELECT 1

    BUCKET BKT

    WHERE DECODE (P_FEE_FLAG, 'FEES', TRUNC(FS.) FEE_DATE), TRUNC (FS. FEE_REFUND_DATE))

    BETWEEN TRUNC (BKT. ACT_START_DATE) AND TRUNC (BKT. ACT_END_DATE)

    944524 wrote:

    Hello Alberto,.

    Thank you that's what I ask but is it possible to verify the condition even using decode

    Yes, it is possible, but why?

    Just replace the query in this way:

    select *
      from fee_table f
    where exists(select 1
                    from bucket b
                  where decode(:p_fee_flag, 'FEE', f.fee_date, f.fee_refund_date) between b.act_start_date and b.act_end_date)
      and decode(:p_fee_flag, 'FEE', null, f.fee_date) is null;
    

    Kind regards.

    Alberto

  • Is a foreign key MUST have a UNIQUE or PK column as a reference?

    First I tried, from what I saw Yes it must be Unique or PK. Secondly, I am pretty sure that I read somewhere where there are PK or unique. Thirdly, I checked oradocs and other pages, the thing ends, I owe an answer

    Constraint foreign key (also called a constraint referential integrity) designates a column as a foreign key and establishes a relationship between this foreign key and a primary or unique key specified, called the referenced key.


    This implies, but does not explicitly specify that it MUST be a PK or a SINGLE.


    Basically I want a simple yes/no answer just to give me some peace of mind. I don't want to waste any time, but changes to the oracle from time to time, and I'd rather have a confirmation from someone with more knowledge/experience.


    Thank you!

    Yes.

    This same document you are referencing tells you what are the rules for the creation of a foreign key.

    Data integrity

    Foreign key constraints

    Whenever two tables have one or more common columns, Oracle database can apply the relationship between the two tables with a foreign key, also called a referential integrity constraint constraint. The constraint requires that for each value in the column on which the constraint is defined, the value in the other specified that another table and column must match. An example of a referential integrity rule is that an employee may work for only one Department.

    Table 5-2 lists the terms associated with referential integrity constraints.

    Table 5-2 referential integrity constraint conditions

    Term Definition

    Foreign key

    The column or set of columns included in the constraint definition that refers to a key that is referenced. For example, the department_id column employees is a foreign key that refers to the department_id column of departments .

    Foreign keys can be described as several columns. However, a composite foreign key must refer to a primary or unique key with the same number of columns and the same types of data.

    The value of the foreign keys can be either the primary or unique key value referenced or be null. If any column of a composite foreign key is null, then the portions not null the key do not match any corresponding part of a parent key.

    Referenced key

    The unique key or the primary key of the table referenced by a foreign key. For example, the department_id column departments is the key referenced to the department_id column of employees .

    Table dependent or child

    The table containing the foreign key. This table is based on the values present in the primary or unique key referenced. For example, the employees table is a child of departments .

    Referenced or the parents table

    The table that is referenced by the foreign key of the child table. It is the key to this table reference that determines whether specific inserts or updates are allowed in the child table. For example, the departments table is a parent of employees .

    The first three terms defined in the table EXPLICITLY State references to the 'core' or 'unique' keys to the parent.

    The doc also refers to the Application Developer Guide:

    Maintaining the integrity of the data in Database Applications

    Foreign key references a primary key by default

    If the list of columns is not included in the REFERENCES option when you set a FOREIGN KEY constraint (simple or composite column), then Oracle database assumes that you want to reference the primary key of the specified table. You can also explicitly specify the columns to reference the table parent in parentheses. Oracle database checks automatically to check this list of column refers to a primary or unique to the parent table key. If it isn't, an informative error is returned.

    That the entire paragraph is as explicitly as it gets.

    No list of columns? Oracle then checks for a primary key.

    There is a list of columns? Then Oracle 'control to verify this list of column made reference to a primary or unique key'...

Maybe you are looking for

  • Mavericks usb recovery

    Hello world I'm stuck trying to create a Mavericks USB of my MacBook Air recovery. One of my mac had a hard drive died, so I will try to reinstall the Mavericks. I downloaded the dmg to the app store, and then the trouble started. I use DiskMaker X o

  • Satellite L505 - installation of Windows 7 can't find driver for the DVD

    Hello I bought a Satellite L505 with Windows 7 home 64 bit. Now, I want to install Windows 7 Professional 64 bit. However when the installation starts he reports that it cannot find a driver for the DVD. Who can help Concerning P. Engels

  • What is the nature of the defragmentation process?

    I noticed that the defragmentation process notably improves the performance of the computer. I would like to know what is actually happening during this process and how often this should be done?

  • BEFSR41 Ver 3 connection to the modem Motorola 2210 problem

    I have a simple (I hope) home office network configuration.  I have a router Linksys BEFSR41 Ver 3, a Vonage phone device, a couple of computers and printers all hooked into the router.  The problem appeared when my old modem is dead.  I replaced the

  • HP probook 4520 CDDVDW not reading DVDs but it is reading the cd

    My CDDVDW not reading DVDs but it is reading the cd, when I check in the management of the computer-> properties of the drivers-> details-> driver description shows me the cd rom value why?