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

Similar Messages

  • Adding Constraints to an existing table

    Hi,
    I've consulted the forum, documentation, the internet and text books but cannot find the correct SQL command to add constraints to an existing table
    Obviously I would
    ALTER TABLE Turkey ADD CONSTRAINT Whitemeat
    But what comes next is puzzling, the values of column Whitemeat can be any value other than Dinner, Gravy, Pumpkin, or Sauce
    Any assistance would be great
    Thank You

    Hi,
    user8998591 wrote:
    Sorry,
    This is what I'm trying to run
    ALTER TABLE TURKEY add
    CONSTRAINT TURKEY_WHITEMEAT_CK CHECK WHITEMEAT NOT IN ('Dinner', 'Gravy', 'Pumpkin', 'Sauce');And this is the error message I am getting
    Error report:
    SQL Error: ORA-00906: missing left parenthesis
    00906. 00000 -  "missing left parenthesis"
    *Cause:   
    *Action:Thank you for your assistanceSee the [SQL Language manual|http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_3001.htm#sthref5176] for the correct syntax.
    The condition after the keyword CHECK has to be in parentheses.
    To add a CHECK constraint to an existing table, I think you have to modify the column.
    ALTER TABLE turkey
    MODIFY  ( whitemeat     CONSTRAINT     turkey_whitemeat_ck
                     CHECK          ( whitemeat NOT IN ( 'Dinner'
                                                , 'Gravy'
                                          , 'Pumpkin'
                                          , 'Sauce'
         )                    )             );Edited by: Frank Kulash on Jan 22, 2010 4:37 PM

  • How to add an unique column to an existing table?

    How to add an unique column to an existing table?
    I have a large table which has no unique constraint. and I want to add an unique column for it. How to do it?
    Does adding a sequence is a good choice? How to do it?
    Thank you

    Hi,
    alter table tablename
    add constraint contraint_name unique (columnname);but before that you need to check in the table.column there is no duplicate record exist.
    Does adding a sequence is a good choice?
    Your talking about unique constraint then yes.
    Regards,
    Taj

  • How add primary key constraint to already existing table with data

    I want apply primary key constraint to already existing table with data
    is there any command or way to do

    Alternatively, assuming you want to ensure uniqueness in your primary key column you can do this:
    alter table <table name> add constraint <cons name> primary key (col1,col2) exceptions into <exception_table>
    If the altter table statement fails this will populate the EXCEPTIONS table with the rows that contain duplicate values for (col1,col2).
    You will need to run (or get a DBA to run) a script called UTLEXCPT.SQL (which will be in the $ORACLE_HOME/rdbms/admin directory) if you don't already have an EXCEPTIONS table.
    Cheers, APC

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

  • Issue in adding not null constraint on 250 G  table with 50 million rows.

    Guys,
    I need to add not null constraint on 2 column of a table with 50 million rows and ~250 GB in size, These 2 columns are newly added and I have also update the value for each of these columns to not null for each row.
    After that I am adding not null constraint on these 2 columns this is taking 1 hour to complete, Is there any way to speed up this, I don't want to use ENABLE NOVALIDATE option or rather I can't use that option.

    user445775 wrote:
    Guys,
    I need to add not null constraint on 2 column of a table with 50 million rows and ~250 GB in size, These 2 columns are newly added and I have also update the value for each of these columns to not null for each row.
    After that I am adding not null constraint on these 2 columns this is taking 1 hour to complete, Is there any way to speed up this, I don't want to use ENABLE NOVALIDATE option or rather I can't use that option.And what's wrong with it taking an hour? Presumably, this is a one time operation, and it doesn't really interfere with anything else.

  • Tip: Unique Constraint on Part of Table

    Here's a cute little trick I picked up from where it was hiding deep within one of the manuals:
    Consider a table where one column needs to be unique, but only part of the time based on some condition within the row. For example, col1 must be unique when its value is above 1000 but any number of rows can have the same value for col1 when it is 999 or less. Another example would be a flag column that determines that col1 must be unique. Don't ask me WHY you would do either of these things.
    Here's how to accomplish the first example (btw both examples require a PK on the table):
    CREATE TABLE junk(
    junk_key INTEGER NOT NULL,
    col1 INTEGER NOT NULL,
    CONSTRAINT pk_junk PRIMARY KEY(junk_key)
    --The way we accomplish this is with a function-based index. 
    CREATE UNIQUE INDEX idx_semiuniq ON junk(
    CASE WHEN col1>=1000 THEN TO_CHAR(col1) ELSE '~' || TO_CHAR(junk_key) END);
    --The following statements should succeed:
    insert into junk values(1,1);
    insert into junk values(2,1);
    insert into junk values(3,1000);
    insert into junk values(4,1001);
    update junk set col1=1002 where junk_key=4;
    --The following statements should fail:
    insert into junk values(5,1000);
    update junk set col1 = 1001 where junk_key=1;
    The same strategy applies to the second example, except that in this case we'll need an additional column to indicate that col1 needs to be unique:
    CREATE TABLE junk( junk_key INTEGER NOT NULL,
    col1 INTEGER NOT NULL,
    uniq_flag CHAR(1) NOT NULL,
    CONSTRAINT pk_junk PRIMARY KEY(junk_key),
    CONSTRAINT ck_junk CHECK (uniq_flag IN ('Y','N'))
    CREATE UNIQUE INDEX idx_semiuniq ON junk(CASE WHEN uniq_flag = 'Y' THEN TO_CHAR(col1) ELSE '~' || TO_CHAR(junk_key) END);
    --these should succeed:
    insert into junk values(1,1,'N');
    insert into junk values(2,1,'N');
    insert into junk values(3,1,'Y');
    insert into junk values(4,2,'Y');
    --these should fail:
    insert into junk values(5,2,'Y');
    update junk set uniq_flag='Y' where junk_key=2;
    Another way to accomplish this is with a "not exists" in a check constraint, but I think the function-based index will perform better especially when inserting or updating large numbers of rows.

    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.

  • Adding a box(subform) to an existing table

    Hi there,
    Just wondering if its possible to add a small box attached to the outside of a dynamic table.I want the box to be attached to the bottom right of the table approximatetly 1/5 of the width of the table.As the table expands the box will remain intact and flow with the table.
    Thanks

    Nevermind,I figured it out

  • Unique constraint control in data table

    I developped a form where the user can enter or modify a list of profiles.
    Each profile has a code (entered by the user).
    I need to control that the profile code is unique.
    What are the recomendations?
    Should I do that control in the validation method, in the action method, or should I let this control to the database and manage an excpetion (but how...) ?
    Do you have an example of such controls?

    Thanks for your answer.
    Actually, this is what I'm trying to do, but it's not so obvious:
    1 - I need to control the unicity of the code in the list. So, I need to have all the new values before validating. The "Validator" attribute doesn't apply to the datatable.
    2 - I want to verify the codes with other rows in the DB (which can be hidden on this screen). So, should I access to the DB from the managed bean just to verify?
    I don't know if it's possible, but what I'd like is to try to do the insert, then the DB will send back an exception, but then, I don't know how to manage this exception. Because if I try to insert, I'm at the end of the lifecycle. I'm not any longer in the validation phase.

  • 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

  • Insert called before delete in a collection with unique constraint

    Hi all,
    I have a simple @OneToMany private mapping:
    private Collection<Item> items;
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    public Collection<Item> getItems() {
    return items;
    public void setItems(Collection<Item> items) {
    this.items = items;
    public void customize(ClassDescriptor classDescriptor) throws Exception {
    OneToManyMapping mapping = (OneToManyMapping)
    classDescriptor.getMappingForAttributeName("items");
    mapping.privateOwnedRelationship();
    I have a unique constraint on my Items table that a certain value cannot be duplicated.
    My problem appears when I remove a previously saved item from the collection and add a new item containing the same data, at the same time.
    After I save the parent and do a flush, I receive SQLIntegrityConstraintViolationException because TopLink performs first an insert query instead of deleting the existing item.
    I tested the application and everything went fine with: remove item / save parent / insert item / save parent
    I checked on the Internet and the documentation but didn't find anything similar to my problem. I tried debugging TopLink's internal calls but I'm missing some general ideas about all the inner workings and don't know what to look for. I use TopLink version: Oracle TopLink Essentials - 2.1 (Build b60e-fcs (12/23/2008))
    Does anyone have a hint of what to look for?
    Edited by: wise_guybg on Sep 25, 2009 4:01 PM
    Edited by: wise_guybg on Oct 5, 2009 11:22 AM

    Thank you for the suggestions James
    As I mentioned briefly I have done some debugging but couldn't understand how collections are updated. What I did find out is that setShouldPerformDeletesFirst() doesn't come into play in this case because this is not a consecutive change on entities.
    What I have in my case is a collection inside an entity that the user has tampered with and now TopLink has to do a merge. I cannot call flush() in the middle since the user has not approved that the changes made to the entity should be saved.
    I see that for TopLink it's not easy to figure out the order in which changes were made to a collection. Here is pseudo-code of when the constraint is touched:
    entity.items.remove(a)
    entity.items.add(b)
    merge(entity)
    And here is code that executes without a problem:
    entity.items.remove(a)
    merge(entity)
    entity.items.add(b)
    merge(entity)
    So once again, I think that collection changes are managed differently but I don't find a way to tell TopLink how to handle them. Any ideas?

  • Foreign key also refer to unique constraint??

    foreign key also refer to unique constraint.
    (GREAT...)
    1.then table that containt unique constraint act as master table??
    2.IS unique constraint will replace with primary key??
    3.Is unique constraint+not null gives all fuctionality as primary key constraint in ???
    4.if primary key=unique+not null then what is use of primary key????????????
    thanks
    kuljeet pal singh

    When you are establishing a foreign key relationship between two tables, a child record must point to a unique record in the parent table. Typically, the child record points to the primary key of the parent, although any unique field or fields in the parent will do.
    So, a table with a unique constraint can act as a parent table in a foreign key relationship.
    A unique constraint may be replaced with a primary key, but not neccessarily.
    A unique constraint plus a not null constraint is functionally identical to a primary key.
    The principle benefit of a primary key compared to unique plus not null is that it provides additional information to someone looking at the database. The primary key is the unchanging identifier for a particular record. A unique constraint plus a not null constraint only implies uniqueness. It is somewhat common for unique values to change over time, as long as they remain unique, but a primary key should never change.
    TTFN
    John

  • Unique Constraint

    Hello,
    OWM_VERSION: 11.1.0.7.0
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    I have a situation where somewhere along the line the primary key for a few records were thrown off. This is causing workspace manager to try and insert the T-520575 workspace records into LIVE when they are merged back together however this causes a unique constraint violation. Here is what the data looks like:
    PK       UNQ1    UNQ2    WORKSPACE
    2095989  495685  152568  T-520575
    491685  495685  152568  LIVE
    2095990  495687  152569  T-520575
    491687  495687  152569  LIVE
    2096052  495689  152570  T-520575
    491689  495689  152570  LIVEI tried deleting the records out of the T-520575 workspace and refreshing the table using the following, but it still raises the unique constraint.
       delete from table
        where PK in( 2095989, 2095990, 2096052);
       dbms_wm.refreshtable(
          workspace    => 'T-520575',
          table_id     => 'TABLE',
          where_clause => 'PK in ( 491685, 491687, 491689)',
          auto_commit  => FALSE
       );   I can see that the records I deleted have a WM_OPTYPE of 'D' but do not have a retiretime. How do I retire these records so that I can refresh them from LIVE? or is there a better solution to correct this issue?
    Edit
    I should also add that LIVE is the parent of this workspace T-520575
    Thanks,
    Tyson
    Edited by: Tyson Jouglet on Apr 27, 2012 8:34 AM

    Hi Tyson,
    Are you sure there are no other rows that have a conflicting value for the unique constraint? What you have described should work. Since the rows have been deleted, they are no longer considered when evaluating the constraints when executing RefreshTable. You should be able to both merge and refresh the workspace after deleting the rows. Also, the row(s) with the 'D' wm_optype would not have a retiretime value, unless the row was reinserted. Only the 'I' or 'U' row(s) would have a retiretime value in this case.
    If there are not any other rows, then I would need a more complete description. Are there any continuously refreshed workspaces that have T-520575 as a parent workspace? Those workspaces would also have to be checked.
    Regards,
    Ben

  • Adding a Unique and Referential Constraint to  XMLType of Purchase Table

    SQL> desc XDBPO_TYPE
    XDBPO_TYPE is NOT FINAL
    Name Null? Type
    SYS_XDBPD$ XDB.XDB$RAW_LIST_T
    messageType VARCHAR2(4000)
    MessageHeader XDBPO_MESSAGEHEADER_TYPE
    Order XDBPO_ORDER_CLLT
    SQL> desc XDBPO_MESSAGEHEADER_TYPE
    XDBPO_MESSAGEHEADER_TYPE is NOT FINAL
    Name Null? Type
    SYS_XDBPD$ XDB.XDB$RAW_LIST_T
    version VARCHAR2(50)
    payloadId VARCHAR2(4000)
    transmissionAgent VARCHAR2(4000)
    timeStamp VARCHAR2(20)
    senderName VARCHAR2(150)
    senderComponent VARCHAR2(150)
    documentReferenceId VARCHAR2(50)
    documentReferenceIdType VARCHAR2(50)
    dataCleansingDocumentId VARCHAR2(50)
    singleTransaction VARCHAR2(4000)
    Configuration XDBPO_CONFIGURATION_TYPE
    HeaderIndexedAttribute XDBPO_HIATTRIBUTE_CLLT
    I following the example in the demo in
    Adding a Unique and Referential Constraint to Table Purchaseorder
    which the constraint is added to the reference field.
    but for my case, i need to add my constraint
    to MessageHeader/@payloadId
    how do i go about in adding the constraint?
    tried to use this syntax logic but not successful:
    alter table purchaseorder
    add constraint REFERENCE_IS_UNIQUE
    unique (xmldata."Reference")
    Anyone have any idea? Mark?
    Thanks.

    nevermind i solved the problem already
    i will just post the solution incase someone else wants to add constraint to the sub xmltype object
    alter table purchaseorder
    add constraint REFERENCE_IS_UNIQUE
    unique (xmldata."MessageHeader"."payloadId");

  • Insert result of query into a table with unique constraint

    Hi,
    I have a query result that I would like to store in a table. The target table has a unique constraint. In MySQL you can do
    insert IGNORE into myResultTable <...select statement...>
    The IGNORE clause means if inserting a row would violate a unique or primary key constraint, do not insert the row, but continue inserting the rest of the query. Leaving the IGNORE clause out would cause the insert to fail and an error to return.
    I would like to do this in oracle... that is insert the results of a query that are not already in the target table. What is the best way to do this? One way is use a procedural language and loop through the first query, checking to see if each row is a duplicate before inserting it. I would think this would be slow if there are lots of records. Other options...
    insert into myTargetTable
    select value from mySourceTable where ... and not exists (select 'x' from myTargetTable where value = mySourceTable.value)
    insert into myTargetTable
    select mySourceTable.value
    from myTargetTable RIGHT JOIN mySourceTable
    ON myTargetTable.value = mySourceTable.value
    where ...
    and myTargetTable.value IS NULL
    any other suggestions?
    Thanks,
    Simon

    Try doing a MINUS instead of not exists., ie Source MINUS Target.
    Disabling the constraint will not help you since this will allow the duplicate rows to be inserted into the table. I don't think you want this.
    --kalpana                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • MPEG2 codec not working in Final Cut Pro on Mac OSX Tiger

    We have been using the File-export-Quicktime Conversion-MPEG2 codec for exporting of files from Final Cut Pro to DVD Studio Pro. On the new mac system that was just bought, the option does not show up. Currently the system is running Quicktime Pro 7.

  • Is there anyway I can run a faster OS on my G4 Powerbook (pre Intel)?

    I was very kindly given a G4 Powerbook by my uncle, but after waiting a whole year to get it I was heartbroken to realise I could not sync my iPhone 5 as it needs to run a faster OS to be able to run iTunes 11. My mum established it is a pre Intel pr

  • DKA790GX Platinum - What's the best card that will work with hybrid crossfire?

    Hi everyone. I know this board is a bit old now but I've set it up for my kids to play oldish games and it occurred to me that video cards from that era might be inexpensive these days. What's the best possible card to use with the on-board card for

  • Not a GROUP BY expression - Oracle 10g bug?

    Hi, I am geting 00979. 00000 - "not a GROUP BY expression" error on Oracle 10g 10.2.0.4.0 - 64bit Production. To illustrate my problem I created following example. Let think I have some shop with clothes. Everytime I sell something, I store this info

  • Ma clé usb ne s'affiche pas sur mon mac

    Salut, J'ai un petit problème: ma clé usb ne s'affiche pas sur mon mac (ni sur mon bureau, ni dans utilitaire du disque), alors qu'elle s'affiche sur d'autres Mac. Ce n'est pas non plus le port usb qui a un problème car quand je la branche elle s'all