Disable ingegrity constraint, then re-enable w/deletion of violations?

Suppose table2 has a foreign-key relationship with table1. Is there any way to disable that constraint on table2, delete a huge number of records from table1, then re-enable the constraint on table 2... telling Oracle to simply delete any records it finds in table2 that no longer satisfy the constraint?
Or, alternatively, is there a way to cascade the deletes, but defer the cascaded deletion until all the records that are going to be deleted from the current table have, in fact, been deleted (or at least marked for deletion)?
For the record, the real situation is nowhere near this trivial... we have a table with ~2 billion records that's partitioned by range on its primary key (from which we want to drop a partition containing ~300 million records) and has dozens of downstream tables with foreign key relationships leading back to it.
The good news is that this isn't a database that has to be kept online and available at all times for continual transaction processing. The foreign-key relationships are mainly there for the sake of academic correctness and self-documentation, and the records being purged are ancient and haven't even been part of a table scan for months. So we're not the least bit worried about having a row in table27 spend two hours on "death row" between the time its deletion becomes inevitable (by virtue of deleting an upstream record with a foreign-key chain leading back to it) and the time it gets physically deleted. Metaphorically, we just need a fast way to slice a chunk off from table1 with a chainsaw, then efficiently eliminate the witnesses from the downstream tables with a meat cleaver. :-)

OK, let's suppose table1 is the big table with billions of records, from which I'm going to drop the first partition and ~250 million records contained within it.
table2 has a foreign key relationship: table2.foo_id = table1.id
table3 has a foreign key relationship to table2: table3.bar = table2.bar
both foreign key relationships are deferrable, initially deferred.
Now, partition #1 gets dropped, taking ~250 million records with it. I'm going to guess that the implicit commit comes at the end of that drop, and that's the point when Oracle officially notices that table2 has a foreign key relationship with table1 and parses through it to cascade the deletion and remove the newly-orphaned rows in table2.
The big question is, when does table2's constraint come into effect? If Oracle defers the next implicit commit attempt until it finishes purging orphaned records from table2, then proceeds to cascade the deletion and purge orphaned records from table3 before its next attempted implicit commit, that's great.
HOWEVER, I can see a conflict. DROP is a DDL statement that implicitly commits, but what about any DELETEs that get cascaded from it as an outcome of the drop? Do they fall under the single umbrella of the original DROP, or does something like this happen:
Partition #1 of table1 gets dropped. implicit commit attempted, but foreign key relationship between table2 and table1 formally noticed. Oracle deletes the first orphaned row from table2, then tries to autocommit it... and notices that table3 has a FK relationship with table2. So it scans through table3, deletes any rows that the deletion of the first row from table2 will orphan, and autocommits that deletion. It then continues looking through table2 for the next orphaned row, deletes it, attempts to autocommit, notices the FK constraint (again) between table3 and table2, scans through table3 (again) looking for rows that will be orphaned by the deletion of the second row from table2, deletes them, and autocommits. Then repeats, over and over again, scanning all of table3 from top to bottom each time it deletes a row from table2.
I have to admit I'm a little fuzzy about what exactly Oracle is doing ACID-wise behind the scenes, mainly because nothing I normally do really requires moment-to-moment integrity. All I really use transactions for is to conveniently undo the mess and restore the database to its original state if a program crashes for some reason, and try to sidestep them (and their overhead) entirely when I'm doing something manually with Toad or SQL*Plus that's time-consuming and doesn't need to keep the database in any kind of usable state between the time it starts and ends. But in the case of deferred integrity checks, I can see how encouraging Oracle to autocommit could actually make performance worse, by prematurely firing otherwise-deferrable constraints.

Similar Messages

  • DISABLE VALIDATE CONSTRAINT에 관하여(8I NEW)

    제품 : ORACLE SERVER
    작성날짜 : 2002-11-05
    DISABLE VALIDATE CONSTRAINT에 관하여(8I NEW)
    ===========================================
    개 요
    =======
    간단하게 설명하면, enable/disable은 향후 DML작업으로 추가되는 데이터에 대해
    constraint를 설정/해제한다는 의미이고,
    validate/novalidate는 constraint를 설정/해제할 때 기존 데이터의 constraint를
    보장하거나 보장하지 않는다는 것이다.
    아래에서 Version별 Constraint를 정리하였고, 여러 가지 설정에 각각에 대하여
    살펴보기로 한다.
    V7 V8 V8i
    enable enable validate* enable validate*
    enable novalidate enable no validate
    disable disable disable validate
    disable novalidate*
    * default
    1. ENABLE VALIDATE
    과거의 데이터건 향후의 데이터건 모든 데이터에 대해서 constraint를
    보장함을 의미.
    2. ENABLE NOVALIDATE
    향후의 모든 DML은 constraint의 적용을 받으나 기존 데이터에 대한 constraint는
    보장하지 않는다.
    3. DISABLE NOVALIDATE
    오라클은 더이상 모든 데이터에 대한 constraint를 보장하지 않는다.
    4. DISABLE VALIDATE
    설정된 constraint는 해제되고, 사용된 index는 drop된다. 그러나 table에 대한
    모든 DML은 허락되지 않기 때문에 기존 데이터의 constraint는 보장된다.
    즉 table은 freezing 되어 query만 허용된다.
    DISABLE VALIDATE의 용도
    ======================
    이 기능은 data warehousing에서 유용하게 이용될 수 있다. 우선 index 공간을
    절약하면서 uniqueness를 보장받을 수 있다.
    또한 range-partitioned table에 대량 데이터를 exchange partition 기능으로
    적재할 경우, 추가되는 partition의 데이터에 대해 constraint를 validate하기 위한 table scan을 하지 않으므로 성능을 향상시킬 수 있다.
    (물론 partition key와 PK key가 같아야 한다)
    만약 constraint가 DISABLE VALIDATE된 table에 DML작업을 실행하면 에러가 발생.
    ORA-25128: No insert/update/delete on table with
    constraint (x.x) disabled and validated
    DISABLE VALIDATE 예제
    =====================
    CREATE TABLE tbl_emp (
    empno NUMBER CONSTRAINT pk_emp PRIMARY KEY,
    ename VARCHAR2(20)
    SELECT constraint_name,validated,status FROM user_constraints
    WHERE table_name = 'TBL_EMP' ;
    CONSTRAINT_NAME VALIDATED STATUS
    PK_EMP VALIDATED ENABLED
    SELECT index_name , status FROM user_indexes
    WHERE table_name = 'TBL_EMP' ;
    INDEX_NAME STATUS
    PK_EMP VALID
    ALTER TABLE tbl_emp MODIFY CONSTRAINT pk_emp DISABLE VALIDATE ;
    SELECT constraint_name,validated,status FROM user_constraints
    WHERE table_name = 'TBL_EMP' ;
    CONSTRAINT_NAME VALIDATED STATUS
    C1 VALIDATED DISABLED
    SELECT index_name , status FROM user_indexes
    WHERE table_name = 'TBL_EMP' ;
    no rows selected
    delete from tbl_emp
    ERROR at line 1:
    ORA-25128: No insert/update/delete on table with constraint (SCOTT.PK_EMP) disabled and validated

  • I'm looking to remotely disable then re-enable a NIC ... possible?

    My organization is having quite a few issues now that we're finally rid of XP. We think we've narrowed it down to the default setting of Win 7 NIC cards Power Management, specifically the "Allow the computer to turn off this device to save power"
    checkbox being enabled (checked). Example below:
    We've had hundreds of complaints of disconnects and issues re-connecting when people leave their computer at lunchtime or an extended break, and on a few dozen of those specific people we have tried disabling this (manually) and they report the issue has
    stopped for them. We'd like to test this on a few dozen more people, but they're at remote locations and we'd have to do it remotely. Making the actual change isn't a problem, it's a specific registry key located at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\
    - the problem is the NIC needs to be disabled and re-enabled after changing the key to make it stick, otherwise it seems to revert back to a default (which is that box checked on).
    Does anyone know of a way to disable and then re-enable a NIC on a remote machine via PowerShell? We have full remote access to these machines, so we can copy scripts to them or invoke-command if need be.
    Thanks in advance.
    [email protected]

    If running PowerShell V3, you can take advantage of disconnected remote sessions to continue running code even if the session has been disconnected (and in theory should work if the NIC drops).
    Something like this should work:
    #Create the session option; Drop is important so the command execution continues on after the disconnect
    $Option = New-PSSessionOption -OutputBufferingMode Drop
    $Session = New-PSSession -ComputerName 'client1' -SessionOption $Option
    Invoke-Command -Session $Session -ScriptBlock {
    #Registry code work goes here
    $NetAdapter = Get-WMIObject Win32_NetworkAdapter -filter "Name='Intel(R) 82579LM Gigabit Network Connection'"
    $NetAdapter.Disable()
    $NetAdapter.Enable()
    #This may not be needed since the connection will drop anyways
    Disconnect-PSSession $Session
    #Wait a bit and see if the system comes up as the commands should still be running remotely
    Note: The clients need to be running V3 for this to work.
    Boe Prox
    Blog |
    Twitter
    PoshWSUS |
    PoshPAIG | PoshChat |
    PoshEventUI
    PowerShell Deep Dives Book

  • I cannot Disable a constraint in SQL Developer

    Here is my issue:
    I have created a table already named practice1.
    Using SQL Developer PL/SQL try to run a loop as following:
    DECLARE
    COUNTER1  NUMBER(2);
    BEGIN
    COUNTER1 := 30;
    ALTER TABLE practice1
    DISABLE  CONSTRAINT PRK1;
    LOOP
    COUNTER1 := 30;
    INSERT INTO PRACTICE1
    VALUES (COUNTER1, 'test7', 8, 9);
    EXIT WHEN  COUNTER1 >26;
    END LOOP;
    END;
    In other words I Insert the COUNTER1 variable value as Primary Key in the tables field1 column.
    I run the script successfully without the ALTER TABLE DISABLE CONTSRAINT.. command.
    Everytime I run it I had to increase the starting value of Variable COUNTER1 so it will not attempt to insert a duplicate pre-existed value in Primary Key.
    Then I decided to insert the command ALTER TABLE DISABLE CONSTRAINT in order to not have to worry to change the starting value.
    I am able to disable the constraint by using the same command in isolation . If I run it as part of the script as above I get the following error:
    Error report:
    ORA-06550: line 5, column 1:
    PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
       ( begin case declare end exception exit for goto if loop mod
       null pragma raise return select update while with
       <an identifier> <a double-quoted delimited-identifier>
       <a bind variable> << continue close current delete fetch lock
       insert open rollback savepoint set sql execute commit forall
       merge pipe purge
    06550. 00000 -  "line %s, column %s:\n%s"
    *Cause:    Usually a PL/SQL compilation error.
    *Action:
    I would appreciate any suggestions.
    Thank you.

    Your question has NOTHING to do with sql developer.
    Mark this question ANSWERED and repost it in the SQL and PL/SQL forum.
    https://forums.oracle.com/community/developer/english/oracle_database/sql_and_pl_sql
    The problem is that you CANNOT execute DDL directly in PL/SQL. You need to use dynamic SQL to execute DDL within PL/SQL.
    EXECUTE IMMEDIATE 'ALTER TABLE . . .';
    If you need more help use the correct forum as shown above.

  • Can I disable a constraint in a stored procedure

    Hi,
    I wish to disable a constraint and then enable after I do a certain insert into a database, In my procedure I put the 'ALTER ..DISABLE' command straight after the begin and the the 'ALTER..ENABLE' just before the exit command but I keep getting a compile error. Any suggestions?

    Since ALTER TABLE is DDL, you would have to use dynamic SQL in order to call it from PL/SQL, i.e.
    BEGIN
      EXECUTE IMMEDIATE 'ALTER TABLE ... DISABLE';
      <<do something>>
      EXECUTE IMMEDIATE 'ALTER TABLE ... ENABLE';
    END;Of course, since you're executing DDL, you'll be implicitly committing after both dynamic SQL statements.
    A better approach, though, may be declare the constraint to be deferrable and do
    EXECUTE IMMEDIATE 'ALTER SESSION SET CONSTRAINTS = DEFERRED'since that doesn't implicitly commit. You can also avoid having to hard-code constraint names in strings in your code. Plus, the constraints will be automatically checked when you commit.
    Justin

  • How to disable all Constraints for a Table

    Hi There,
    So I have a table that I need to delete a significant amount of records from. Using some advice I found it better to select the records that I wanted to keep into a temporary table and then truncate the original table. After that I insert the contents of the temp table into the original table.
    So now I am thinking I could speed this up even more if I disable all the constraints on the original table.
    Is there an easy way to do this or do I need to disable each constraint individually?
    thanks
    John

    http://forums.oracle.com/forums/search.jspa?threadID=&q=disable+all+constraints+&objID=c84&dateRange=all&userID=&numResults=15

  • Stsadm Export "This constraint cannot be enabled as not all values have corresponding parent"

    I am trying to export a sharepoint site using the command "stsadm -o export -url http://prefix.domain.com/sites/sitename -includeusersecurity -filename c:\sitename"
    I have already done this on about 30 other sites.  This site is failing on export with the following message.
    [11/9/2009 3:39:39 PM]: FatalError: This constraint cannot be enabled as not all values have corresponding parent values.
    at System.Data.ConstraintCollection.AddForeignKeyConstraint(ForeignKeyConstraint constraint)
    at System.Data.ConstraintCollection.Add(Constraint constraint, Boolean addUniqueWhenAddingForeign)
    at System.Data.DataRelationCollection.DataSetRelationCollection.AddCore(DataRelation relation)
    at System.Data.DataRelationCollection.Add(DataRelation relation)
    at System.Data.DataRelationCollection.Add(String name, DataColumn[] parentColumns, DataColumn[] childColumns)
    at Microsoft.SharePoint.Deployment.ListItemObjectHelper.GetNextBatch()
    at Microsoft.SharePoint.Deployment.ObjectHelper.RetrieveDataFromDatabase(ExportObject exportObject)
    at Microsoft.SharePoint.Deployment.ListItemObjectHelper.RetrieveData(ExportObject exportObject)
    at Microsoft.SharePoint.Deployment.ExportObjectManager.GetObjectData(ExportObject exportObject)
    at Microsoft.SharePoint.Deployment.ExportObjectManager.MoveNext()
    at Microsoft.SharePoint.Deployment.ExportObjectManager.ExportObjectEnumerator.MoveNext()
    at Microsoft.SharePoint.Deployment.SPExport.SerializeObjects()
    at Microsoft.SharePoint.Deployment.SPExport.Run()
    I checked the SharePoint logs and the error message in there is the exact same.  Nothing is in the windows application error logs.
    I looked at what it was trying to do before the error and it failed on a task list.  I tried deleting the task list and trying again and it bombed on a document library next.
    I did some googling and found a hotfix http://support.microsoft.com/kb/955594 I tried to install it, but I have SP2 installed and therefore it said that the expected version was off.  Im assuming since I have SP2 and that hotfix is dated in 08 that it should be included in SP2 anyways.
    Does anyone have an idea on what is going on and how to fix it?  I am trying to migrate this sub site to a new server and set it up as a new site collection.

    Good you caught that ... somethings would have shut down at the 90day mark...
    Would you humor me and tell me what this does.. Note I changed the order of a few things, added a .bak to the filename and also added versions. 
    If this errors would go into the Windows Event Viewer and look for anything SharePoint related, then look at security logs and see if there are any errors. 
    stsadm -o export -url http://prefix.domain.com/sites/sitename -includeusersecurity -filename c:\sitename.bak  -includeusersecurity –versions 4
    Kris Wagner, MCITP, MCTS
    Twitter @sharepointkris
    Blog: http://sharepointkris.com

  • How do I enable flash and java on firefox23 as I have the latest versions installed yet the plugin page shows "disabled" with no option to enable

    I have updated to Firefox 23 and it disabled my Java and Flash plugins. I then updated these to Flash 11.8.800.94 and Java to Version 7 Update 25. Now these are showing up on the plug in page but are showing "disabled" with no option to enable. How do I enable them to view content on the web.

    Thanks Philipp but i have already done that and the content started working...
    However, when i closed and restarted the browser it returned back to the same settings...
    I dont think that should happen, but anyway thank you for the solution. At least I can use it by resetting the values if need be
    Appreciate your help

  • Ever since enabling Soft Delete on one of my tables, the logs are flooded with "... does not support the 'deleted' system property"

    I enabled Soft Delete on one of my Azure Mobile Services tables, and ever since then, the logs are flooded with tons of warnings that say something like this:
    The table 'Section' does not support the 'deleted' system property.
    Is there a way to suppress these warnings, or is it advisable to enable soft delete for all of my tables?
    As a follow on, is there a way to export the logs so that it's easier to peruse through them and search?
    Thanks :)

    Hi
    You can set your logging level in Azure Admin portal to be Error only, so it only logs errors and warnings will be ignored.
    Regards
    Aram

  • My phone was disabled. How do I enable it?

    My phone was disabled. How do I enable it?

    If the iPhone is showing a disabled message because of too many failed passcodes then you will need to connect it to the computer that you normally sync to and you should then be able to reset the phone and re-sync your content to it (http://support.apple.com/kb/HT1212) - you may need to put the iPhone into recovery mode : http://support.apple.com/kb/ht1808

  • Disable a constraints

    hello,
    i want to disable a constraints ,when i tried to disable a constraints iam getting error.the error is
    ora-00054:resource busy and acquired with nowait specified.
    how to over come this error.
    by
    ravikumar

    This message appears when some other user is updating the rows after doing an exclusive lock.So you get this message saying that the resource is busy.
    So you have to wait for that user to commit/rollback his transaction, only then you get go forward with you task

  • ITunes Match is having errors d/l songs to my iPhone 4s. Then I can't delete them, and it says some songs are playing when they aren't. I've restored my iPhone, same issue.

    iTunes Match is having errors d/l songs to my iPhone 4s. Then I can't delete them, and it says some songs are playing when they aren't. I've restored my iPhone, same issue.

    According to this article  Using iPhone on an airplane  you should be able to listen to music with Airplay Mode enabled.
    Make sure you have Music switched on in Settings > Store or your music won't download via Wi-Fi.

  • HT4113 I have an ipod that is disabled.  How do I enable it back when the kids can't remember what the password was?

    I have an ipod that is disabled.  How can I enable it when the kids don't remember the password?

    Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    iOS: Wrong passcode results in red disabled screen                          
    If recovery mode does not work try DFU mode.                         
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings

  • Is there a way to move files from one folder to another without copying and pasting and then going back to delete the original?

    Is there a way to move files from one folder to another without copying and pasting and then going back to delete the original?  The cut and paste function is not available and there's no "move to" function.  Am I missing something?  It was so easy with Windows.

    Drag the files, or press Option when pasting them; this accesses the Move To function.
    (124070)

  • Why is my Apple ID still disabled when supposedly  was fixed by apple httsupport this am over 12 hours agora dithery said it would be disabled no longer then 8 hours and I still am unable to buy anything in the I tunes store or pay for any apps or games

    Why is my Apple ID still disabled when supposedly it was fixed by Apple ID support over the phone  this am over 12 hours ago and they  said it ( my Apple ID and password) would be disabled no longer then 8 hours and I still am unable to buy anything in the I tunes store or pay for any apps or games.

    We are fellow users here on these forums. Have you tried logging out of your account on your iPad by tapping on your id in Settings > iTunes & App Store and then logged in and seeing if it then works ?

Maybe you are looking for

  • URLConnection Posting Large DataFiles

    I am looking for a way to STREAM large data files, say 100MB+ and the HEAP size is say only 32MB. I believe I should be able to simply do what the code shows below..but.. The AcmeUtils.copyStream method simply conks out with java.lang.outOfMemoryErro

  • I am looking for help.....

    Is there a software available, were you can take a pencil drawing of a wolf and merge it with an image of a mountain side or a creek bed, so that the image would look natural enough, but you would still see the wolf in the mountain side or creek bed?

  • Calendars are nowhere to be seen

    Recently noticed that when I start iCal, no events show up, and no calendars are visible. If I flip to day planner view (default at start is month view), events show up, and they are still visible even when I switch back to month view. But the calend

  • Itunes is opening a brand new itunes every time i open my itunes.....

    hi guys.. my itunes has just started doing this lately and i dont know why! when i open itunes its not opening my itunes, it opens a fresh one every time and launches the getting started tutorials too, all my settings have been reset and when i try s

  • Create subVI with while loop

    Hello, i have a big program which is in a while structure and when i try to make a subVI, i have a message which tell me that my selection contain a front pannel which is in a while loop. How can i do to make a subVI? Thanks a lot