HOWTO: Add a UNIQUE constraint to a populated column

Here is the way to add a unique constraint to a populated column, ensuring that the existing values are unique as well.
ALTER TABLE t1
ADD CONSTRAINT t1_uk UNIQUE (col1,col2)
EXCEPTIONS INTO my_exceptions
/If the alter table statement fails this will populate the MY_EXCEPTIONS table with the rows that contain duplicate values for (col1,col2). These are identified by ROWID. We can then chose to:
[list]
[*]delete rows with a bad key;
[*]amend the values of the key columns;
[*]re-apply the constraint with the NOVALIDATE option.
[list]
We should be wary of choosing the NOVALIDATE option. There's usually a good reason why the unique constraint is required and we should not circumvent it. Apart from anything else, Oracle allows us to build foreign keys referencing NOVALIDATE unique keys. This could result in child rows that have two parents, which is normal in biology, but very wrong in a database.
NOVALIDATE is useful in datawarehouses and suchlike, because little updating occurs and the data integrity issues are of less imporatance. I don't think it ought to be used in OLTP situations. The code example at the end of this posting illustrates why we should exercise caution with NOVALIDATE.
Once we have handled the duplicate values we can re-run the alter table statement and apply the constraint.
If you don't already have an EXCEPTIONS table (it can be called anything, it's the structure that counts) you may need to run (or get a DBA to run) a script called UTLEXCPT.SQL, which will be in the $ORACLE_HOME/rdbms/admin directory.
Cheers, APC
SQL> SELECT col1, col2, col3 FROM t1;
      COL1       COL2       COL3                                               
         1          1          0                                               
         2          1          0                                               
         2          1          0                                               
SQL> SELECT col1, col2, cola FROM t2;
      COL1       COL2 COLA                                                     
         1          1  I'm child #1                                                        
         1          1  I'm child #2                                                        
         2          1  I'm child #3                                                        
SQL> ALTER TABLE t1
  2  ADD CONSTRAINT t1_uk UNIQUE (col1, col2);
ALTER TABLE t1 ADD CONSTRAINT t1_uk UNIQUE (col1, col2)
ERROR at line 1:
ORA-02299: cannot validate (TST2.T1_UK) - duplicate keys found We can't add a unique key, so we decide to use the NOVALIDATE clause.
SQL> CREATE INDEX t1_i ON t1(col1, col2);
Index created.
SQL> ALTER TABLE t1
  2  ADD CONSTRAINT t1_uk UNIQUE (col1, col2) ENABLE NOVALIDATE;
Table altered.
SQL> INSERT INTO t1 VALUES (2, 1, 1);
insert into t1 values (2, 1, 1)
ERROR at line 1:
ORA-00001: unique constraint (TST2.T1_UK) violated Well, we can't add any more duplicate keys, so that's alright isn't it? Nope. We can add a foreign key to table T2 referencing T1 but we don't know which row in T1 is the parent of the rows in T2.
SQL> ALTER TABLE t2
  2  ADD CONSTRAINT t2_t1_fk foreign key  (col1, col2)
  3  REFERENCES t1(col1, col2)
Table altered.
SQL> SELECT rowid FROM t1 WHERE col1 = 2;
ROWID                                                                          
AAAVnMAANAAAB96AAB                                                             
AAAVnMAANAAAB96AAC                                                             
SQL> DELETE FROM t1 WHERE rowid = 'AAAVnMAANAAAB96AAB';
1 row deleted.
SQL> DELETE FROM t1 WHERE rowid = 'AAAVnMAANAAAB96AAC';
DELETE FROM t1 WHERE rowid = 'AAAVnMAANAAAB96AAC'
ERROR at line 1:
ORA-02292: integrity CONSTRAINT (TST2.T2_T1_FK) violated - child record found
SQL> ROLL
Rollback complete.
SQL> DELETE FROM t1 WHERE rowid = 'AAAVnMAANAAAB96AAC';
1 row deleted.
SQL> DELETE FROM t1 WHERE rowid = 'AAAVnMAANAAAB96AAB';
DELETE FROM t1 WHERE rowid = 'AAAVnMAANAAAB96AAB'
ERROR at line 1:
ORA-02292: integrity CONSTRAINT (TST2.T2_T1_FK) violated - child record found
SQL>  ROLL
Rollback complete.
Why this matters: queries joining child and parent tables return more rows than we'd expect normally.
SQL> SELECT t2.cola
  2  FROM   t2
  3  WHERE  t2.col1 = 2
  4  and    t2.col2 = 1;
COLA                                                                           
I'm child #3                                                                   
SQL> SELECT t2.cola, t1.col4
  2  FROM   t1, t2
  3  WHERE  t2.col1 = 2
  4  AND    t2.col2 = 1
  5  AND    t1.col1 = 2
  6  AND    t2.col2 = 1;
COLA                    COL4                                                   
I'm child #3            I'm the daddy                                          
I'm child #3            No, I'm the daddy!!                                    
SQL> Caveat emptor
This posting is issued on behalf of the Rogue Moderators. It is posted with the best of intentions but is not guaranteed in any way, shape or form. In particular, the code is presented "as is" and you assume full responsibility for running it on your system. Furthermore, you must not download and install software from the internet unless you know what you are doing and have the permission of whoever owns your system. It was never this hard for the Lone Ranger.

Hi,
You can not create unique key with duplicate values as you know. Now if you want to create unique key then you have to delete duplicate records from the table but this again if you can afford to delete because this data may be more importante to you and you can not delete any record.
or you can use ENABLE NOVALIDATE option of oracle explain by Tom on below link.
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:8806498660292
or if you dont want to use Tom's way then you go with primary key like
Drop old primary key if there is already on the column.
create new primary key with enable novalidate option.

Similar Messages

  • Add a unique constraint on binary XML table

    How add a unique constraint of "brevet" field?
    The following INSERT failed
    SQL Error: ORA-19025: EXTRACTVALUE renvoie la valeur d'un seul noeud
    19025. 00000 - "EXTRACTVALUE returns value of only one node"
    If the ALTER is made after the INSERT is done, INSERT is valid but ALTER failed with the same error message!
    /* copy the file compavions.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <compagnie>
         <comp>AB</comp>
         <flotte>
              <avion immat="F-WTSS" capacite="90">
                   <typeAv>Concorde</typeAv>
              </avion>
              <avion immat="F-GFDR" capacite="145">
                   <typeAv>A320</typeAv>
              </avion>
              <avion immat="F-GTYA" capacite="150">
                   <typeAv>A320</typeAv>
              </avion>
         </flotte>
         <nomComp>Air Blagnac</nomComp>
         <pilotes>
              <pilote>
              <brevet>PL-1</brevet>
              <nom>C. Sigaudes</nom>
              </pilote>
              <pilote>
              <brevet>PL-2</brevet>
              <nom>P. Filloux</nom>
              </pilote>
         </pilotes>
    </compagnie>
    in C:\...
    --DROP DIRECTORY repxml;
    --CREATE DIRECTORY repxml AS 'C:\...';
    DROP TABLE pilote_binary_xml5;
    CREATE TABLE pilote_binary_xml5 OF XMLType
    XMLTYPE STORE AS BINARY XML
    VIRTUAL COLUMNS
    (col AS (EXTRACTVALUE(OBJECT_VALUE, '/compagnie/pilotes/pilote/brevet')));
    ALTER TABLE pilote_binary_xml5 ADD CONSTRAINT brevet_unique UNIQUE (col);
    INSERT INTO pilote_binary_xml5 VALUES (XMLType(BFILENAME ('REPXML','compavions.xml'), NLS_CHARSET_ID ('AL32UTF8')));
    --ALTER TABLE pilote_binary_xml5 ADD CONSTRAINT brevet_unique UNIQUE (col);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You could try something like
    (extract(OBJECT_VALUE,compagnie/pilotes/pilote/brevet').getStringVal());
    but this is probably unadvisable.
    I suggest an alternative is for you to look at XMLINDEX so that you can bring the 'proper' XML functions into play like XMLTABLE etc.

  • Performance Impact of Unique Constraint on a Date Column

    In a table I have a compound unique constraint which extends over 3 columns. As a part of functionality I need to add another DATE column to this unique constraint.
    I would like to know the performance implications of adding a DATE column to the unique constraint. Would the DATE column behave like another VARCHAR2 or NUMBER column, or would it degrade the performance significantly?
    Thanks
    Message was edited by:
    user627808

    What performance are you concerned about degrading? Inserts? Or queries? If you're talking about queries, what sort of access path are you concerned about?
    Are you concerned that merely changing the definition of the unique constraint would impact performance? Or are you worried that whatever functional change you are making would impact performance (i.e. if you are now retaining historical data in the table rather than just updating it)?
    Regardless of the performance impact, unique indexes (and unique constraints) need to be correct. If you need to allow duplicates on the 3 current columns with different dates, then you would need to change the unique constraint definition regardless of the performance impact. Fast and wrong generally isn't going to be preferrable to slow and right.
    Generally, though, there probably is no reason to be terribly concerned about performance here. Indexing a date is no different than indexing any other primitive data type.
    Justin

  • UNIQUE constraint on a varchar column

    I have a (non-key) varchar2 column that I need to be unique. I specify UNIQUE in the table create line like:
    create table tester(
    id number primary key,
    field varchar2(255) UNIQUE
    but it doesn't behave as expected. The following statements don't cause a constraint violation:
    insert into tester values(1,'text');
    insert into tester values(2,'tEXT');
    That is, UNIQUE on a varchar column is case sensitive. How can I create a case-insensitive UNIQUE constraint?
    null

    Take a look at the 'new' feature named function based indexes. I do not now if you can create a unique this way but at least you can try. Keep us informed please.

  • Howto add "With Authorization" for removel to Enrollment Profiles?

    When I enroll a iOS device to our Profile manager it get's an "Remote Management" profile which the user can remove without restriction.
    When I add profiles later on, they are all linked to this firest profile and can all be deleted by deleting the first profile. It doesn't matter if the latter has a removal restriction set.
    So how do I lock the Enrollment Profiles??

    Of course, the previous posting is not really related to this thread and therefore ought to have be posted as a New topic, but seeing as how AS has introduced the subject...
    Here is the way to add a unique constraint to a populated column, ensuring that the existing values are unique as well.
    ALTER TABLE t1
    ADD CONSTRAINT t1_uk UNIQUE (col1,col2)
    EXCEPTIONS INTO my_exceptions
    /If the alter table statement fails this will populate the EXCEPTIONS table with the rows that contain duplicate values for (col1,col2). These are identified by ROWID. We can then chose to:[list]
    [*] delete rows with a bad key;
    [*] amend the values of the key columns;
    [*] re-apply the constraint with the NOVALIDATE option.[list]
    We should be wary of choosing the NOVALIDATE option. There's usually a good reason why the unique constraint is required and we should not circumvent it. Apart from anything else, Oracle allows us to build foreign keys referencing NOVALIDATE unique keys. This could result in child rows that have two parents, which is normal in biology, but very wrong in a database. NOVALIDATE is useful in datawarehouses and suchlike, because little updating occurs and the data integrity issues are of less imporatance. I don't think it ought to be used in OLTP situations.
    Once we have handled the duplicate values we can re-run the alter table statement and apply the constraint.
    If you don't already have an EXCEPTIONS table (it can be called anything, it's the structure that counts) you may need to run (or get a DBA to run) a script called UTLEXCPT.SQL, which will be in the $ORACLE_HOME/rdbms/admin directory.
    Cheers, APC

  • Adding a UNIQUE Constraint to an existing table

    Hi,
    I got this issue because of the existing data. My issue is in my table I want to add a unique constraint to two columns but i cannot add this becuase of the existing repeating data. And I cannot do a data repair to fix the repeating data since the customer is reling on this data so we can not get the decision to repair the data.
    As a solution I try this method, by adding a function to check the repeating data before inserting the data to the table. It's working fine to a user but when it come to multiple users it's not working because users can log to the database and can do their transactions simultaneously.
    My question is; is there a way in oracle to add a constraint to the data that can add in future not to the old existing data?
    Thanks,
    Darex.

    user9359353 wrote:
    Hi,
    As a solution I try this method, by adding a function to check the repeating data before inserting the data to the table. It's working fine to a user but when it come to multiple users it's not working because users can log to the database and can do their transactions simultaneously.
    show us what is "not working". if you are calling this function from a trigger the correct way, the first person to commit will have their data inserted and the next person will not be able to insert.
    edit: you may want to have a read through this thread: where I was encountering a problem with multi-row validation using triggers:
    Row level validation dependant on other rows?
    note this post:
    Rob van Wijk wrote:
    Hi WhiteHat,
    Here are two blogposts of mine about this subject that you might find useful.
    One with some guidelines about implementing entity rules: http://rwijk.blogspot.com/2008/08/implementing-entity->rules.html
    And one with an example how to implement (among others) an overlap check in the context of another option for your >question, the product RuleGen: http://rwijk.blogspot.com/2008/05/rulegen-test.html
    Hope this helps.
    Regards,
    Rob.Edited by: WhiteHat on Jun 8, 2011 3:51 PM

  • Simple unique constraint question

    HI ALL,
    I have created a table as below, and added unique key to both the col of the table.
    CREATE TABLE TT( A NUMBER,B NUMBER);
    ALTER TABLE TT ADD CONSTRAINT UNQ_CNT UNIQUE(A,B);
    INSERT INTO TT VALUES (&A,&B);
    Enter value for a: 1
    Enter value for b: null
    Enter value for a: 1
    Enter value for b: null
    ORA-00001: unique constraint (SCOTT.UNQ_CNT) violatedwhy I am getting the above err as Null cannot be equal to Null so the record
    should be unique from other record.
    Kindly help in understanding this concept.
    Regards,
    AAK.

    AAK,
    When you create UNIQUE constraint on multiple
    NULLABLE columns, uniqueness is checked for NON-NULL
    values. So in your case, when you try to insert
    another row, ORACLE detects that column A already has
    same value (1) and hence it gives error. You can find
    more details in documentation.Two rows that contain nulls for one or more key columns and the same
    combination of values for the other key columns violate the constraint.
    Not for NON-NULL values only.
    Khurram

  • Unique constraint violation on version enabled table

    hi!
    we're facing a strange problem with a version enabled table that has an unique constraint on one column. if we rename an object stored in the table (the name-attribute of the object is the one that has a unique constraint on the respective column) and rename it back to the old name again, we get an ORA-00001 unique constraint violation on the execution of an update trigger.
    if the constraint is simply applied as before to the now version enabled table, I understand that this happens, but shouldn't workspace manager take care of something like that when a table with unique constraints is version enabled? (the documentation also says that) because taking versioning into account it's not that we try to insert another object with the same name, it's the same object at another point in time now getting back it's old name.
    we somewhat assume that to be a pretty standard scenario when using versioned data.
    is this some kind of bug or do we just miss something important here?
    more information:
    - versioning is enabled on all tables with VIEW_WO_OVERWRITE and no valid time support
    - database version is 10.2.0.1.0
    - wm installation output:
    ALLOW_CAPTURE_EVENTS OFF
    ALLOW_MULTI_PARENT_WORKSPACES OFF
    ALLOW_NESTED_TABLE_COLUMNS OFF
    CR_WORKSPACE_MODE OPTIMISTIC_LOCKING
    FIRE_TRIGGERS_FOR_NONDML_EVENTS ON
    NONCR_WORKSPACE_MODE OPTIMISTIC_LOCKING
    NUMBER_OF_COMPRESS_BATCHES 50
    OWM_VERSION 10.2.0.1.0
    UNDO_SPACE UNLIMITED
    USE_TIMESTAMP_TYPE_FOR_HISTORY ON
    - all operations are done on LIVE workspace
    any help is appreciated.
    EDIT: we found out the following: the table we are talking about is the only table where the unique constraint is left. so there must have been a problem during version enabling. on another oracle installation we did everything the same way and the unique constraint wasn't left there, so everything works fine.
    regards,
    Andreas Schilling
    Message was edited by:
    aschilling

    hi!
    we're facing a strange problem with a version enabled table that has an unique constraint on one column. if we rename an object stored in the table (the name-attribute of the object is the one that has a unique constraint on the respective column) and rename it back to the old name again, we get an ORA-00001 unique constraint violation on the execution of an update trigger.
    if the constraint is simply applied as before to the now version enabled table, I understand that this happens, but shouldn't workspace manager take care of something like that when a table with unique constraints is version enabled? (the documentation also says that) because taking versioning into account it's not that we try to insert another object with the same name, it's the same object at another point in time now getting back it's old name.
    we somewhat assume that to be a pretty standard scenario when using versioned data.
    is this some kind of bug or do we just miss something important here?
    more information:
    - versioning is enabled on all tables with VIEW_WO_OVERWRITE and no valid time support
    - database version is 10.2.0.1.0
    - wm installation output:
    ALLOW_CAPTURE_EVENTS OFF
    ALLOW_MULTI_PARENT_WORKSPACES OFF
    ALLOW_NESTED_TABLE_COLUMNS OFF
    CR_WORKSPACE_MODE OPTIMISTIC_LOCKING
    FIRE_TRIGGERS_FOR_NONDML_EVENTS ON
    NONCR_WORKSPACE_MODE OPTIMISTIC_LOCKING
    NUMBER_OF_COMPRESS_BATCHES 50
    OWM_VERSION 10.2.0.1.0
    UNDO_SPACE UNLIMITED
    USE_TIMESTAMP_TYPE_FOR_HISTORY ON
    - all operations are done on LIVE workspace
    any help is appreciated.
    EDIT: we found out the following: the table we are talking about is the only table where the unique constraint is left. so there must have been a problem during version enabling. on another oracle installation we did everything the same way and the unique constraint wasn't left there, so everything works fine.
    regards,
    Andreas Schilling
    Message was edited by:
    aschilling

  • Unique constraint violation error

    Hello All,
    I have a procedure called - FHM_DASHBOARD_PROC which inserts the data into a table called FHM_DASHBOARD_F fetching records from several tables. However, for a particular type of record, that data is not being inserted because of the Unique constraint violation
    the procedure is:
    create or replace
    PROCEDURE FHM_DASHBOARD_PROC AS
    DB_METRICS_CNT1Z number;
    --V_PODNAME varchar2(10);
    V_KI_CODE_DB_STATSZ varchar2(50);
    V_ERRORSTRING varchar2(100);
    --CURSOR PODNAME_CUR IS SELECT PODNAME,SHORTNAME FROM CRMODDEV.POD_DATA WHERE PODSTATUS_ID=1 AND PODTYPE_ID=1 ORDER BY PODNAME;
    -- DB STATS
    BEGIN
      -- OPEN PODNAME_CUR;
        --   LOOP
          --   FETCH PODNAME_CUR INTO V_PODNAME,V_POD_SHORTNAME ;
            -- EXIT WHEN PODNAME_CUR%NOTFOUND;
               BEGIN
                     SELECT COUNT(*) INTO DB_METRICS_CNT1Z FROM FHM_DB_METRICS_F A, FHM_DB_D B where A.DBNAME=B.DBNAME and PODNAME=V_PODNAME AND DB_DATE=TRUNC(SYSDATE-1);
                               DBMS_OUTPUT.PUT_LINE('DB_METRICS_CNT1Z :'|| DB_METRICS_CNT1Z);
                               IF DB_METRICS_CNT1Z >0 THEN
                        DBMS_OUTPUT.PUT_LINE('DB STATS');
                       INSERT INTO FHM_DASHBOARD_F(PODNAME,DASH_DATE,KI_CODE,KI_VALUE,KI_STATUS)
                          (SELECT PODNAME, DASH_DATE AS CU_DATE, KI.KI_CODE, NVL(PF.KI_VALUE,0),
                                                                  CASE
                                                                   WHEN PF.KI_VALUE = ki.warning_threshold then 2
                        when PF.KI_VALUE=0 then 0
                        ELSE 1
                        END  AS ALERT_STATUS
                        FROM
                        (SELECT PODNAME,DB_DATE AS DASH_DATE,decode(a.stats_last_status,'SUCCEEDED',1,'FAILED',2,'STOPPED',2,NULL,0) KI_VALUE from 
                        FHM_DB_METRICS_F a,fhm_db_d b where a.dbname=b.dbname and podname='XYZ' and db_date=TRUNC(SYSDATE-1) and dbtype='OLTP')PF,
                        FHM_KEY_INDICATOR_D KI where PF.PODNAME=KI.POD_NAME AND KI.TIER_CODE=3 AND KI.KI_NAME='DB_STATS'
                        AND (PF.PODNAME,TRUNC(PF.DASH_DATE),KI.KI_CODE) NOT IN (SELECT PODNAME,DASH_DATE,KI_CODE FROM FHM_DASHBOARD_F));
                                 COMMIT;
                             ELSE
                                    SELECT KI_CODE INTO V_KI_CODE_DB_STATSZ FROM FHM_KEY_INDICATOR_D WHERE POD_NAME=V_PODNAME AND KI_NAME='DB_STATS';
                                     DBMS_OUTPUT.PUT_LINE('V_KI_CODE_DB_STATSZ :'||V_KI_CODE_DB_STATSZ);
                                     INSERT INTO FHM_DASHBOARD_F(PODNAME,DASH_DATE,KI_CODE,KI_VALUE,KI_STATUS) VALUES(V_PODNAME,TRUNC(SYSDATE-1),V_KI_CODE_DB_STATSZ,0,0);
                                     COMMIT;
                             END IF;
         EXCEPTION
                            WHEN OTHERS THEN
                            V_ERRORSTRING :='INSERT INTO FHM_DASHBOARD_F_ERROR_LOG(POD_NAME,KI_NAME,ERRORNO,ERRORMESSAGE,DATETIME) VALUES
                   ('''||V_PODNAME||''',''DB_STATS'','''||SQLCODE||''','''||SQLERRM||''',SYSDATE)';                        
                   EXECUTE IMMEDIATE  V_ERRORSTRING;
                            COMMIT;
              END;
          --END LOOP;
      --CLOSE PODNAME_CUR;
    END;
    END FHM_DASHBOARD_PROC;and the table where the data is inserting is
    CREATE TABLE "CRMODDEV"."FHM_DASHBOARD_F"
        "PODNAME" VARCHAR2(25 BYTE) NOT NULL ENABLE,
        "DASH_DATE" DATE,
        "KI_CODE"   NUMBER NOT NULL ENABLE,
        "KI_VALUE"  NUMBER,
        "KI_STATUS" NUMBER,
        CONSTRAINT "FHM_DASHBOARD_F_DATE_PK" PRIMARY KEY ("DASH_DATE", "PODNAME", "KI_CODE") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 NOLOGGING COMPUTE STATISTICS STORAGE(INITIAL 4194304 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "CRMODDEV_IDX" ENABLE,
        CONSTRAINT "FHM_DASHBOARD_F_KI_CODE_FK" FOREIGN KEY ("KI_CODE") REFERENCES "CRMODDEV"."FHM_KEY_INDICATOR_D" ("KI_CODE") ENABLE
      PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS NOLOGGING STORAGE
        INITIAL 3145728 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT
      TABLESPACE "CRMODDEV_TBL" ENABLE ROW MOVEMENT ;the Primary key constraint is FHM_DASHBOARD_F_DATE_PK and is on 3 columns of the table DASH_DATE, PODNAME, KI_CODE
    And this is the query used in the Procedure for inserting the data into the table
    (SELECT  PODNAME, DASH_DATE AS CU_DATE, KI.KI_CODE, NVL(PF.KI_VALUE,0),
                                   CASE
                                   WHEN PF.KI_VALUE = ki.warning_threshold then 2
    when PF.KI_VALUE=0 then 0
    ELSE 1
    END  AS ALERT_STATUS
    From
    (Select  Podname,Db_Date As Dash_Date,Decode(A.Stats_Last_Status,'SUCCEEDED',1,'FAILED',2,'STOPPED',2,Null,0) Ki_Value From  -- Added Distinct
    FHM_DB_METRICS_F a,fhm_db_d b where a.dbname=b.dbname and podname in ('XYZ') and db_date = TRUNC(SYSDATE-2) and dbtype='OLTP')PF,
    Fhm_Key_Indicator_D Ki Where Pf.Podname=Ki.Pod_Name And Ki.Tier_Code=3 And Ki.Ki_Name='DB_STATS'
    And (Pf.Podname,Trunc(Pf.Dash_Date),Ki.Ki_Code) Not In (Select Podname,Dash_Date,Ki_Code From Fhm_Dashboard_F));It gives *2 record* as result
    XYZ 20-JAN-12     2521     1     1
    XYZ 20-JAN-12     2521     1     1
    So it gives Unique constraint violation error while inserting. Then, I changed in the above inserting code by adding a distinct clause. After that the query gives only ONE record as result. However, that record also is not being inserted into the table and giving the same error.
    Now the question is How shall I insert this record into the table successfully ?
    Though the message is too long, However, I have given you the full structure of the object/procedure and error.
    Thank You in Advance.

    when you have 5 columns in the result set adding DISTINCT is n ot the solution as you may get the same error again.
    Check the target table whether the data exists before inserting ..if not check the table structure for unique constraint created on other columns.
    select *from <table_name>
    where
    DASH_DATE=date '2012-01-20'
    and PODNAME='XYZ'
    and  KI_CODE=2521;

  • UNIQUE constraint vs checking before INSERT

    I have a SQL server table RealEstate with columns - Id, Property, Property_Value. This table has about 5-10 million rows and can increase even more in the future. I want to insert a row only if a combination of Id, Property, Property_Value does not exist
    in this table.
    Example Table -
    1,Rooms,5
    1,Bath,2
    1,Address,New York
    2,Rooms,2
    2,Bath,1
    2,Address,Miami
    Inserting 2,Address,Miami should NOT be allowed. But, 2,Price,2billion is okay. I am curious to know which is the "best" way to do this and
    why. The why part is most important to me.
    Check if a row exists before you insert it.
    Set unique constraints on all 3 columns and let the database do the checking for you.
    Is there any scenario where one would be better than the other ?
    Thanks.

    Why? 
    Because the database engine does exactly what you want - it is designed to do this in a way that anticipates collisions with simultaneous inserts and allows only a single row for any given combination of values.  If you choose to manage this at the
    application level - which is the alternative you propose - then EVERY application that attempts to insert rows must be designed to both check immediately before insertion and immediately afterwards (since these inserts can occur simulateously and you must
    allow for communication delays between database and client).  And since we know that programmers are not infallible (many other adjectives come to mind as well), there exists a high probability that the duplicate checking logic will fail.  And do
    not forget that there are many ways of inserting data into the table - it is not just your front-end application that must use this logic - it is also every other application that is used to manage data (such as SSMS, SSIS, bcp, etc.) 

  • Problem arises adding unique constraint

    Dear all
    The problem I am facing while adding a unique constraint(based on 2 columns) is ,the table has already duplicate records.I am unable to delete those duplicate records as it has several child record table and those child tables are parent of another table.....and so on. I dont want to use ON DELETE CASCADE.any kind of suggestion?

    Hi,
    If you want to delete the duplicates you can but that is upto you.
    You can delete the duplicate rows by disabling all foreign key constraints.
    SQL> ED
    Wrote file afiedt.buf
      1  select constraint_name,constraint_type,STATUS
      2  from user_constraints
      3* where table_name='EMP'
    SQL> /
    CONSTRAINT_NAME                C STATUS
    PK_EMP                         P ENABLED
    FK_DEPTNO                      R ENABLED
    SQL> ALTER TABLE EMP DISABLE CONSTRAINT FK_DEPTNO;
    Table altered.
    SQL> select constraint_name,constraint_type,STATUS
      2  from user_constraints
      3  where table_name='EMP'
      4  ;
    CONSTRAINT_NAME                C STATUS
    PK_EMP                         P ENABLED
    FK_DEPTNO                      R DISABLED-San
    Edited by: san on Feb 24, 2011 1:02 PM

  • Indices and constraints on XML Tables/Columns (with Schema)

    Hi,
    I've read a lot of documents by know, but the more I read the more I got confused. So I hope you can help me.
    Frist my Oracle Server Version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit
    I've manages to create a table with a column with the type SYS.XMLTYPE and the storage modle "Object Relational" with an XML Schema.
    I can insert data and I can execute XQuery statements.
    I can also create an XMLTYPE table with my Schema, althoug the tool SQL Developer keeps telling me, that the one column wich is generated within the table is of the type CLOB instead of object realtional (which is what I defined).
    The query for that is:
    CREATE TABLE ENTRY_XML OF XMLTYPE
    XMLTYPE STORE AS OBJECT RELATIONAL
    XMLSCHEMA "BBMRI_Entry.xsd" ELEMENT "Entry";
    That's where I am, now my questions:
    1. What's the difference? I'm aware of the obviouse difference, that with the first way I can add relational columns as well, but apart from that? If I only want to store the xml data, is the second approach always better (especially in regard to my next question)?
    2. My schema contains elements with attributes (which contain IDs), which have to be unique. So I tried to add a UNIQUE constraint, but failed. I found this (http://www.oracle.com/technology/sample_code/tech/java/codesnippet/xmldb/constraints/Specify_Constraints.html), but it just doesn't work.
    Query: "ALTER TABLE ENTRY_XML CONSTRAINT ENTRY_XML_SUBID_UNQIUE UNIQUE (xmldata."SubId");"
    Error: "ORA-01735: invalid ALTER TABLE option"
    3. I didn't try yet, but I need to specifiy foreign keys within the XML as well (which is explained in the link at question 2). I guess the solution to question 2 will make this possible as well.
    4. Since I can create a UNIQUE constaint for attributes (well, I can't yet, but I hope that this will change soon) I woundered if it would be possible to realize something like auto_increment. Although I see the problem with validating the xml input if the Ids are empty. Any suggestions on that problem? Do I have to query for the highest (free) id before I can insert the new documents?
    Well, that's enough for today, I hope someone can help me!
    Greetings, Florian

    I've read through all the literature (again) and found out, that I did most of the stuff right in the first place. I just missinterpreted the generated tables for the types and wondered why they only contained one column. Well, at least one mistery solved.
    But know to make it easier just one question, which might solve all problems I have:
    How can I create UNIQUE constraints and FOREIGN KEYS when I have a table or column of the type XmlType with a schema using the object relational storage method?
    I found a solution http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14259/xdb05sto.htm#i1042421 (Example 5-12), but it just does not work for me.
    I removed the FOREIGN KEY and tried it again and the UNIQUE Key works.
    So basically the question is how to retrieve the "AId" Attribute. "XMLDATA"."AId", "XMLDATA"."Attribute"."AId" and "XMLDATA"."Subject"."Attribute"."AId" all do not work.
    I've added my schema declarations at the bottom (which I've already successfully registred and used without foreign keys and constraints, so they work).
    After I've registered the two schema files 3 types and 11 tables where created. One type for the attribute, one for the study type and one probably to link the attributes to the study types. The tables are one for the attribute, 4 for the content*-elements, 2 for the study type (I don't really know why two) and 4 with strange names starting with "SYS_NT" and then some random numbers and letters (looks alot like some base64 encoded string).
    The Query I try to use to create the table is: (The table "Attribute" already exists and contains a field "ID", which is it's PK.)
    CREATE TABLE STUDYTYPE_XML
    OF XMLType (UNIQUE ("XMLDATA"."STId"),
    FOREIGN KEY ("XMLDATA"."AId") REFERENCES ATTRIBUTE(ID))
    XMLTYPE STORE AS OBJECT RELATIONAL
    ELEMENT "StudyType.xsd#StudyType";
    The error I get is:
    Error starting at line 1 in command:
    CREATE TABLE STUDYTYPE_XML
    OF XMLType (UNIQUE ("XMLDATA"."STId"),
    FOREIGN KEY ("XMLDATA"."AId") REFERENCES ATTRIBUTE(ID))
    ELEMENT "StudyType.xsd#StudyType"
    Error at Command Line:3 Column:37
    Error report:
    SQL Error: ORA-22809: nonexistent attribute
    22809. 00000 - "nonexistent attribute"
    Cause: An attempt was made to access a non-existent attribute of an
    object type.
    Action: Check the attribute reference to see if it is valid. Then retry
    the operation.
    Attribute-Schema (Attribute.xsd):
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
         <xs:attribute name="AId">
              <xs:simpleType>
                   <xs:restriction base="xs:integer">
                        <xs:minInclusive value="0" />
                   </xs:restriction>
              </xs:simpleType>
         </xs:attribute>
         <xs:attribute name="Name" type="xs:string" />
         <xs:element name="ContentString" type="xs:string" />
         <xs:element name="ContentInteger" type="xs:integer" />
         <xs:element name="ContentDouble" type="xs:decimal" />
         <xs:element name="ContentDate" type="xs:date" />
         <xs:element name="Attribute">
              <xs:complexType>
                   <xs:choice minOccurs="0" maxOccurs="1">
                        <xs:element ref="ContentString" />
                        <xs:element ref="ContentInteger" />
                        <xs:element ref="ContentDouble" />
                        <xs:element ref="ContentDate" />
                   </xs:choice>
                   <xs:attribute ref="AId" use="required" />
                   <xs:attribute ref="Name" use="optional" />
              </xs:complexType>
         </xs:element>
    </xs:schema>
    Study Type Schema (StudyType.xsd):
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
         <xs:include schemaLocation="Attribute.xsd" />
         <xs:attribute name="STId">
              <xs:simpleType>
                   <xs:restriction base="xs:integer">
                        <xs:minInclusive value="0" />
                   </xs:restriction>
              </xs:simpleType>
         </xs:attribute>
         <xs:element name="StudyType">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element ref="Attribute" minOccurs="1" maxOccurs="unbounded" />
                        <xs:element ref="StudyType" minOccurs="0" maxOccurs="unbounded" />
                   </xs:sequence>
                   <xs:attribute ref="STId" use="required"/>
              </xs:complexType>
         </xs:element>
    </xs:schema>
    Edited by: alwaysspam on Sep 8, 2010 5:35 PM

  • Add unique constraint only if it not exists

    hello racle community,
    I would like to create a unique constraint (at least over two columns) on several tables via a script. Is there any way to fire the ALTER TABLE statement only when a constraint over the same columns does not exists already ? Or do I have to query the USER_CONSTRAINTS table first ?
    Ikrischer

    Yes, something like this:
    set serveroutput on
    declare
      UNIQUE_CONS_EXISTS exception;
      pragma  exception_init(UNIQUE_CONS_EXISTS, -2261); 
    begin
      for r in (select table_name
                      ,rownum rn
                from all_tables where ....) loop
        begin
          execute immediate 'alter table ' || r.Table_Name || ' add constraint i_' || r.rn || ' unique (col1,col2)';
          when UNIQUE_CONS_EXISTS then
            dbms_output.put_line(sqlerrm);
          end;
      end loop;
      dbms_output.put_line('Done');
    end;
    /The only thing to bear in mind is that your constraint names will simply be numbered increments and will have no meaning.

  • Error while adding Image: ORA-00001: unique constraint

    Dear all,
    I have an error while adding images to MDM I can´t explain. I want to add 7231 images. About 6983 run fine. The rest throws this error.
    Error: Service 'SRM_MDM_CATALOG', Schema 'SRMMDMCATALOG2_m000', ERROR CODE=1 ||| ORA-00001: unique constraint (SRMMDMCATALOG2_M000.IDATA_6_DATAID) violated
    Last CMD: INSERT INTO A2i_Data_6 (PermanentId, DataId, DataGroupId, Description_L3, CodeName, Name_L3) VALUES (:1, :2, :3, :4, :5, :6)
    Name=PermanentId; Type=9; Value=1641157; ArraySize=0; NullInd=0;
    Name=DataId; Type=5; Value=426458; ArraySize=0; NullInd=0;
    Name=DataGroupId; Type=4; Value=9; ArraySize=0; NullInd=0;
    Name=Description_L3; Type=2; Value=; ArraySize=0; NullInd=0;
    Name=CodeName; Type=2; Value=207603_Img8078_gif; ArraySize=0; NullInd=0;
    Name=Name_L3; Type=2; Value=207603_Img8078.gif; ArraySize=0; NullInd=0;
    Error: Service 'SRM_MDM_CATALOG', Schema 'SRMMDMCATALOG2_m000', ERROR CODE=1 ||| ORA-00001: unique constraint (SRMMDMCATALOG2_M000.IDATA_6_DATAID) violated
    Last CMD: INSERT INTO A2i_Data_6 (PermanentId, DataId, DataGroupId, Description_L3, CodeName, Name_L3) VALUES (:1, :2, :3, :4, :5, :6)
    Name=PermanentId; Type=9; Value=1641157; ArraySize=0; NullInd=0;
    Name=DataId; Type=5; Value=426458; ArraySize=0; NullInd=0;
    Name=DataGroupId; Type=4; Value=9; ArraySize=0; NullInd=0;
    Name=Description_L3; Type=2; Value=; ArraySize=0; NullInd=0;
    Name=CodeName; Type=2; Value=207603_Img8085_gif; ArraySize=0; NullInd=0;
    Name=Name_L3; Type=2; Value=207603_Img8085.gif; ArraySize=0; NullInd=0;
    I checked all data. There is no such dataset in the database. Can anybody give me a hint how to avoid this error.
    One thing I wonder: The PermanentId is allways the same but I can´t do anything here.
    BR
    Roman
    Edited by: Roman Becker on Jan 13, 2009 12:59 AM

    Hi Ritam,
    For such issues, can you please create a new thread or directly email the author rather than dragging back up a very old thread, it is unlikely that the resolution would be the same as the database/application/etc releases would most probably be very different.
    For now I will close this thread as unanswered.
    SAP SRM Moderators.

  • ORA-00001: unique constraint

    Hi,
    I disabled the primary key of the table to which I insert the data like this :
    INSERT INTO TABLE_X
    select * from table_1 UNION ALL
    select * from table_2 ;
    but I receive this error :
    ORA-00001: unique constraint TABLE_X.PK violated
    Why ? It is already disabled.
    thank you.
    Message was edited by:
    user522961
    Message was edited by:
    user522961
    Message was edited by:
    user522961

    Is it possible you kept the index when disabling the primary key?
    YAS@11G>create table t as select object_id from all_objects where rownum<=10;
    Table created.
    YAS@11G>alter table t add constraint PK_T primary key(object_id);
    Table altered.
    YAS@11G>alter table t disable constraint pk_t;
    Table altered.
    YAS@11G>insert into t select * from t;
    10 rows created.
    YAS@11G>rollback;
    Rollback complete.
    YAS@11G>alter table t enable constraint pk_t;
    Table altered.
    YAS@11G>alter table t disable constraint pk_t keep index;
    Table altered.
    YAS@11G>insert into t select * from t;
    insert into t select * from t
    ERROR at line 1:
    ORA-00001: unique constraint (YAS.PK_T) violated

Maybe you are looking for