Deleting rows from very large table

Hello,
I need to delete rows from a large table, but not all of them, so I can't use truncate. The delete condition is based on one column, something like this:
delete from very_large_table where col1=100;
There's an index (valid, B-tree) on col1, but it still goes very slow. Is there any instruction which can help delete rows faster?
Txh in adv.
A.

Your manager doesn't agree to your running an EXPLAIN PLAN? What is his objection? Sounds like the prototypical 'pointy-hair boss'.
Take a look at these:
-- do_explain.sql
spool explain.txt
-- do EXPLAIN PLAN on target queries with current index definitions
truncate table plan_table
set echo on
explain plan for
<insert query here>
set echo off
@get_explain.sql
-- get_explain.sql
set linesize 120
set pagesize 70
column operation     format a25
column query_plan     format a35
column options          format a15
column object_name     format a20
column order           format a12
column opt           format a6
select     lpad(' ',level) || operation "OPERATION",
     options "OPTIONS",
     decode(to_char(id),'0','COST = ' || NVL(to_char(position),'n/a'),object_name) "OBJECT NAME",
     cardinality "rows",     
     substr(optimizer,1,6) "OPT"
from     plan_table
start     with id = 0
connect by prior id = parent_id
There are probably newer, better ways, but this should work with all living versions of Oracle and is something I've had in my back pocket for several years now. It's not actually executing the query or dml in question, just running an explain plan on it.

Similar Messages

  • How to efficiently select random rows from a large table ?

    Hello,
    The following code will select 5 rows out of a random set of rows from the emp (employee) table
    select *
      from (
           select ename, job
             from emp
           order by dbms_random.value()
    where rownum <= 5my concern is that the inner select will cause a table scan in order to assign a random value to each row. This code when used against a large table can be a performance problem.
    Is there an efficient way of selecting random rows from a table without having to do a table scan ? (I am new to Oracle, therefore it is possible that I am missing a very simple way to perform this task.)
    thank you for your help,
    John.
    Edited by: 440bx on Jul 10, 2010 6:18 PM

    Have a look at the SAMPLE clause of the select statement. The number in parenthesis is a percentage of the table.
    SQL> create table t as select * from dba_objects;
    Table created.
    SQL> explain plan for select * from t sample (1);
    Explained.
    SQL> @xp
    PLAN_TABLE_OUTPUT
    Plan hash value: 2767392432
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |   725 | 70325 |   289   (1)| 00:00:04 |
    |   1 |  TABLE ACCESS SAMPLE| T    |   725 | 70325 |   289   (1)| 00:00:04 |
    8 rows selected.

  • Problem in deleting row from database in table component

    Hi,
    I have a table component that its content change by diffrent links.
    in this table i have a hyperlink in each row to deleting that row from dataBase.
    so i must get the current row .
    i do it like this:
    define a rowset in the page that have a delete query :
    delete from response where responseID=?
    in action of delete hyperlink ,i have:
    Integer responseId=(Integer)responseDataProvider.
    getValue("#{currentRow.value['responseID']}") ;
    getSessionBean1().getResponseRowSet().setObject(1,responseId);
    getSessionBean1().getResponseRowSet().execute();
    but in first line occure a exception:
    illigalArgument #{currentRow.value['responseID']}
    thanks.

    by using data table
    first you should get current record (row that recived action)
    then delete it by using data provider.
    I do not think that you could execute delete statement using rowSets because they just can provide Select statements.
    btw , following code will retrive clicked row from data table and
    delete that row
    try {
    RowKey rk = getTableRowGroup1().getRowKey();
    if (rk != null) {
    testDataProvider.removeRow(rk);
    testDataProvider.commitChanges();
    } catch (Exception ex) {
    log("ErrorDescription", ex);
    error(ex.getMessage());
    hth
    masoud

  • Unable to delete rows from remote db table

    Hi
    I am relatively new to SQL Server and this issue is strange to me.
    In my vb.net code I am opening a connection to local MS Access DB using oledb provider and then am executing below query to remote SQL Server via DBCommand.ExecuteNonQuery();
    DELETE tblStaff.* FROM Staff INNER JOIN [ODBC;Driver=SQL Server;SERVER=<remote ip>;DATABASE=dddddddd;UID=uuuuuuuu;PWD=ppppppppp].tblStaff ON Staff.[Staff ID] = tblStaff.[StaffID] WHERE Staff.[Contact Status] <> "Current"
    This however created below error in the code;
    System.AccessViolationException was unhandled
    Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    Source=System.Data
    StackTrace:
    at System.Data.Common.UnsafeNativeMethods.ICommandText.Execute(IntPtr pUnkOuter, Guid& riid, tagDBPARAMS pDBParams, IntPtr& pcRowsAffected, Object& ppRowset)
    at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
    at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
    at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
    at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
    at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
    During testing I noticed that if I create the relevant table tblStaff in another database on the same remote SQL Server then it works fine, so it appeared to me there is some issue with the original backend db or the table.
    The relevant table tblStaff is related to several tables in the database. I assumed that relations may be an issue so I set the relations to cascade delete even though none of the tables contains any data at this point. This did not work. I then went into
    database diagram, added all the tables and then deleted all relations of the tblStaff table. This did not work either. I then used 'Script Table as..->CREATE to' to script the tblStaff in Management Studio, deleted original tblStaff and ran the create script
    above to recreate the tblStaff table. This worked.
    What is the problem here and why doesn't the table accept delete query in its original form? I appreciate it’s the .net code that creates the error but as the error seems to be related to the backend SQL Server db therefore I have posted it here in case
    someone can help with this.
    Thanks
    Regards

    Sorry I still do not get it. when you say "Its a legacy app", are you talking about the VB.NET app ?
    If so then I repeat my self :-) Why not to connecting to the SQL server directly?
    * even if you need information from several databases (for example ACCESS + SQL Server), in most cases, it is much better to connect directly and get each information to the app. Then in your app you can combine the information and analyse it
    [Personal Site] [Blog] [Facebook]
    Access app is the legacy app. 

  • Oracle  deleting rows from tables starting with the name PQ

    hai friends
    we are given access rights to delete only tables starting with PQ. HAVING PQ_NUM as primary key for all the PQ tables.
    totally we have 6 tables. PQ_01,PQ_02, PQ_03,PQ_04,PQ_05,PQ_06.
    ALL This tables will have one primary key. for example pq_01 willl have pq01_num as primarykey and pq_02 table will have pq02_num as primary
    key.
    pq01_num value will exist in all the primary key of pq tables.
    i want query to delete rows from the pq tables based on the input value i give.
    for example if i give primarykey value 122 then that value in pq tables should be deleted.
    One more problem is there. pq_06 table does not have pq02_num column. here the column differs. it is pq06_num_req.
    so give your idea of deleting the rows from pq tables
    waiting
    S

    I dont have access to databse,this is untested
    declare
      v_cmd  varchar2(2000);
      columnname varchar2(30);
    input_value number:=??;
    tabowner varchar2(30):=???
    begin
    --step 1 identify table
      FOR sub IN (SELECT table_name table_to_delete
      FROM all_tables
    WHERE table_name LIKE 'PQ%'
    and owner=tabowner
    ) LOOP
      ----step 2 identify column
    v_cmd :='select t.column_name from all_constraints S,All_Ind_Columns T where
    S.OWNER=T.TABLE_OWNER
    AND S.TABLE_NAME=T.TABLE_NAME
    AND S.INDEX_NAME=T.INDEX_NAME
    and s.owner=tabowner
    AND S.TABLE_NAME='||table_to_delete||'
    and s.constraint_type='''P'';
         execute immediate v_cmd into columnname; 
         --step 3 delete records
        v_cmd := 'delete from '||tabowner||'.' ||
                 sub.table_to_delete || '
       where '||columnname||'='||input_value; 
         execute immediate v_cmd;
        commit;
         END LOOP; 
    end;Edited by: user5495111 on Aug 11, 2009 6:35 AM

  • Deleting rows from a table matching values from an ascii file

    Hi All,
    I have an ASCII file with 12,000 lines. Each line represents a value (you may call this as bad data) that matches a database column value in table. I have to delete all the rows from a database table (~ 400,000 rows) where a column value matches the bad data value. Linux is the OS is where SQLPLUS client is installed and I can execure any SQL queries from this Linux server. Oracle DB server is 10g.
    Any input on how to do this will be helpfull to me. I am not a database programmer so if any details will be appreciated.
    Thanks

    Hi,
    That's going to be very slow (among other problems) if you don't have the bad data in a table. An index-organized table would probably be best.
    Assuming the data data are uinique strings, up to 30 characters long, and that you don't need any other columns, you can create a table like this:
    CREATE TABLE  bad_data
    (   bad_txt    VARCHAR (30)
    ,  CONSTRAINT  bad_data_pk  PRIMARY KEY (bad_txt)
    ) ORGANIZATION INDEX;SQL*Loader is one way of getting the data from the file (doesn't have to be on the database server; it can be on your client machine) into the table.
    Once you have a table, actually removing the rows from the big table might be as simple as:
    DELETE  big_table
    WHERE   column_a  IN
            (   SELECT  bad_txt
                FROM    bad_data
    ;

  • Deleting a row from a UIData table

    I am trying to select a row from a jsf table then call a backing bean method to delete it using this backing bean method.
    void deleterow(){
    dataitem =(item) dataTable.getrowdata();
    List newlist = new ArrayList();
    table = model.getwrappeddata();
    for (int i=0; i<table.size(); i++){
        product = (product)table.get(i);
       if (!product.name.equals(dataitem.name)){
          newlist.add(product);
    model.setwrappeddata(newlist);
    }all the getter/setter methods are set and it does seem to work.However the results are very inconsistent,sometimes rows are deleted and then magically reappear on the the table latter! Anyone knows of a fail proof method of achieving this?
    Ta.

    A decent IDE ships with a code debugger which allows you tracking variables and running code step by step. If you don't use an IDE or you're unable to use it, then just add some sysouts which prints the desired variables at strategic locations and/or moments.

  • Prevent user from deleting rows from all tables in his own schema

    Hi,
    How can I prevent user from deleting rows in all tables in his own schema.
    I want the user to not able to delete rows from any existing or new tables that might be added in the future.
    The user does not have the "DELETE ANY TABLE" system privilege.
    Please advise.
    Thanks.

    Nowadays, I'd also avoid triggers (if possible).
    Sometimes, when I daydream, I'm rewriting a few applications that I've contributed to as a newbie, and I'm very ashamed of it nowadays.
    From what I've experienced, in retrospective, the emphasis on teaching 'Oracle stuff' has been lying far too much on PL/SQL row-by-row oriented processing instead of letting Oracle 'crunch' sets at once.
    Most of my debugging hours ended up in discovering one or more database triggers 'doing stuff automagically'.
    Another nice blogpost: http://rwijk.blogspot.com/2007/09/database-triggers-are-evil.html
    Regarding OP's question:
    I would just rethink/reconsider this requirement completely.
    Correctly implementing privileges and roles seems the best way to go, yes.
    Triggers? Nah...
    pre-post-edit, noticed thread got updated just before posting
    Don't know what you mean with 'namedropping', but I think it's legitimate to point other readers to interesting Oracle related opinions/articles that do have a technical background and lots of interesting examples.
    post dreaded OTN outage edit (from here)
    Again: I would just rethink/reconsider this requirement completely.
    Both trigger/vpd are being used to hide a design flaw here.

  • Deleting rows from a table

    COuld anyone tell me how to delete rows from a table which has millions of rows.
    TIA,
    Oracle user

    if you are deleting all the rows, use "truncate table" in sql*plus.
    or if you are deleting all but a handful of rows, then copy the rows you still want to a spare table, drop the original table, and rename the spare table back to the original table's name.
    hope this helps

  • Deleting a row from the item table

    Hi All,
    I have a requirement where I need to put a button to delete the selected row from the item table and for this I have written the following code:
    DATA lo_nd_t_bseg TYPE REF TO if_wd_context_node.
        DATA lo_el_t_bseg TYPE REF TO if_wd_context_element.
        DATA ls_t_bseg TYPE wd_this->element_t_bseg.
        data: it_tab type table of wd_this->element_t_bseg.
      lo_nd_t_bseg = wd_context->path_get_node( path = `Z.T_BSEG` ).
      lo_el_t_bseg = lo_nd_t_bseg->get_element( ).
      lo_el_t_bseg->get_static_attributes(
        IMPORTING
          static_attributes = ls_t_bseg ).
        lo_nd_t_bseg = wd_context->path_get_node( path = `Z.T_BSEG` ).
        lo_el_t_bseg = lo_nd_t_bseg->get_element( ).
        IF lo_el_t_bseg IS not INITIAL.
          lo_nd_t_bseg->remove_element( lo_el_t_bseg ).
        ENDIF.
    Now the problem is although it's deleteing the selected line correctly but because of this I am losing one line on the screen for the user to enter... my form has a fixed number of lines and in my case it's 10... so everytime I am using deleting a line item I am losing one line to enter..... can you please tell me how can I avoid this?
    Edited by: rajatg on Aug 4, 2011 3:12 PM

    lets say...
    i have 1,2,3 documents
    i have cleared , document 2....
    1. when the user selects this record.... you can read the context_element....using the context element you can get the values and clear those values and set the blank values...
    when the user click on save ...you can have only those two records in the table.
    2. conitnue with your logic .... remove_element. once it is done ,,, create_element at the deleted index...
    3. when clicked on delete ...remove_element ( current code).... bind the table to the node... and you will have ur values

  • Delete rows from table...Bizarre problem.

    Folks
    i HAVE this bizarre problem.
    I hava a Java class which displays data read into a table with a delete
    option by the side of each row.
    Now lets assume you have 3 rows in the Table.
    abc deleteButton
    efg deleteButton
    xyz deleteButton
    When I click the first delete,that row gets deleted from the table.(perfect...)
    Now I have 2 rows.
    When I click on the first row,I get the error
    'You clicked -1'
    java.lang.ArrayIndexOutofBoundsException: -1 < 0.
    Can anyone tell me why this is happening even though there are rows in the table.???
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("You clicked row : " + table.getSelectedRow());
    javax.swing.table.TableModel model = table.getModel();
    Object o = model.getValueAt(table.getSelectedRow(),0);
    //System.out.print(model.getValueAt(table.getSelectedRow(), 0));
    //System.out.println();
    MyDeleteFunction(o.toString());
    // Delete row from window.
    ((DefaultTableModel)table.getModel()).removeRow(table.getSelectedRow());
    table.revalidate();
    table.repaint();

    Hi ritu,
    This class is called
    new DisplayCall_IDTodisconnect(hashTable);
    its a long file.
    its attached below.
    The rows are displayed by reading a hashtable into a vector
    and the vector is iterated and appended..
    public class DisplayCall_IDToDisconnect {
    public static JTable createTable(Vector data, String buttonLabel, ActionListener action){
    return createTable(data.iterator(), buttonLabel, action);
    public static JTable createTable(
    Iterator dataIterator,
    String buttonLabel,
    ActionListener action) {
    DefaultTableModel model = new DefaultTableModel() {
    public boolean isCellEditable(int row, int col) {
    return col == 1;
    model.setColumnCount(2);
    while (dataIterator.hasNext()) {
    Object[] row = { dataIterator.next().toString(), null };
    model.addRow(row);
    DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
    columnModel.addColumn(new TableColumn(0, 100));
    columnModel.addColumn(new TableColumn(1, 80,
    new TableButtonCellRenderer(buttonLabel),
    new TableButtonCellEditor(buttonLabel, action)
    JTable table = new JTable(model, columnModel) {
    public void valueChanged(ListSelectionEvent e) {
    super.valueChanged(e);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    return table;
    private static class TableButtonCellRenderer implements TableCellRenderer {
    final JButton button;
    TableButtonCellRenderer(String buttonLabel) {
    button = new JButton(buttonLabel);
    public Component getTableCellRendererComponent(
    JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus, int row, int column) {
    return button;
    private static class TableButtonCellEditor
    extends AbstractCellEditor
    implements TableCellEditor, ActionListener {
    final JButton button;
    final ActionListener callback;
    TableButtonCellEditor(String buttonLabel, ActionListener callback) {
    button = new JButton(buttonLabel);
    this.callback = callback;
    button.addActionListener(this);
    public Component getTableCellEditorComponent(
    JTable table,
    Object value,
    boolean isSelected,
    int row, int column) {
    return button;
    public Object getCellEditorValue() {
    return null;
    public void actionPerformed(ActionEvent e) {
    button.getParent().requestFocus();
    callback.actionPerformed(e);
    static JTable table;
    Vector items;
    final ClientManager clientMgr;
    // Constructor.
    public DisplayCall_IDToDisconnect(Hashtable callLegTable,ClientManager clientMgr){
    Vector vCSeqnos = displayCSeqNos(callLegTable);
    this.clientMgr = clientMgr;
    JFrame frame = new JFrame("Disconnect Options");
    /*Vector*/ items = new Vector();
    Enumeration vEnum = vCSeqnos.elements();
    while(vEnum.hasMoreElements()){
    items.add(vEnum.nextElement());
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    //System.out.println("You clicked row ,col: " + table.getSelectedRow()+
    // table.getSelectedColumn());
    javax.swing.table.TableModel model = table.getModel();
    Object o = model.getValueAt(table.getSelectedRow(),0);
    System.out.print(model.getValueAt(table.getSelectedRow(), 0));
    System.out.println();
    closeConnection(o.toString());
    // Delete row from window too.
    ((DefaultTableModel)table.getModel()).removeRow(table.getSelectedRow());
    table.revalidate();
    table = DisplayCSeqNos.createTable(items, "Disconnect", al);
    frame.getContentPane().add(new JScrollPane(table));
    frame.pack();
    frame.show();
    } // End Constructor.
    public void closeConnection(String s){
    /*1. Disconnect the current session*/
    this.clientMgr.disconnectCall(s);
    /*2. refresh the Disconnect window*/
    this.refreshWindow();
    public Vector displayCSeqNos(Hashtable callLegTable){
    Enumeration eNum;
    String str;
    Vector v = new Vector();
    eNum=callLegTable.keys();
    while(eNum.hasMoreElements()){
    str = (String) eNum.nextElement();
    //System.out.println("Key : " + str + " Value : " + callLegTable.get(str));
    v.addElement(str);
    return v;
    } // End of displayCSeqNos.

  • How to delete rows from multiple tables when pressing button

    Hi, I'm wondering how do I delete a row from two different tables at the same time when I press the Delete button. Both tables have GROUP_ID as their primary key.

    Nevermind! I realized that I had "reset" before my process to delete from the 2nd table.

  • Deleting rows from one table while filter condition lies into another table

    Hi All,
    I'm facing a problem deleting a row from a table where the condition lies in other table. To ealaborate the scenario further let's say I have two table T1 (transaction table) and T2 (Master Table). I want to delete a record from table T1 by checking some conditions lies in table T2.
    I tried with the below query but this query deleting records from both the table.
    DELETE FROM ( SELECT * FROM T1 top INNER JOIN T2 tp
    ON top.TID = tp.TID
    WHERE top.DEAL_SITE_ID = inputparameter1
    AND (TP.SEGMENT <>inputparameter2 OR tp.segment is not null));
    Here the record is getting deleted from both the tables but I don't want to delete data from my master table i.e table T2.
    Any help would be highly appreciated. Thanks in advance.
    Regards,
    Subhadeep

    SQL> select *
      2   from the_table;
    X          Y
    AA         a
    BB         a
    CC         a
    AA         b
    DD         b
    SQL> select *
      2   from the_table_2;
    X          Y
    AA         a
    BB         a
    CC         a
    SQL>  delete from
      2  (
      3  select *
      4  from the_table  t1 inner join the_table_2 t2
      5  on  t1.x = t2.x
      6  and t1.y = t2.y);
    3 rows deleted.
    SQL> select *
      2   from the_table;
    X          Y
    AA         b
    DD         b
    SQL> select *
      2   from the_table_2;
    X          Y
    AA         a
    BB         a
    CC         a

  • Deleting rows from a JTable

    Hello,
    I've got a JTable which is based on a 2-dimensional array, which contains my data. Now I want to delete several rows from the JTable. There's the possibility to modify my data-array by creating a new array which doesn't contain anymore the datasets I want to delete. Afterwards I can redraw the table and my rows are deleted. But I think that's a very complicated way to delete rows from a JTable. Can anybody tell me whether ther's an easier way to do so ? I'd really be pleased...
    Thanx,
    Findus

    When you create a TableModel using a two-dimensional array or a Vector of Vectors, a DefaultTableModel is created and it stores the data in its own Vector of Vectors. The DefaultTableModel supports methods for adding/removing rows of data. To remove the first row in the table you would do something like:
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.removeRow( 0 );
    Note: once you create the TableModel you should set your array to null as it is not used anymore.

  • Delete Rows from T1 which are Not in T2

    Hi
    I've 2 Tables like below
    T1
    N1
    N2
    2
    11
    2
    22
    3
    33
    8
    44
    8
    88
    T2
    N1
    N2
    2
    22
    8
    88
    If I Run Delete query, I must delete Rows from T1 which are Not in T2
    For example, I must delete Rows 1,3,4 from T1
    So how to write that delete query? Please advice

    Delete from T1
    Where not Exists (select * from T2 Where t1.N1=t2.N1 and t1.N2=t2.N2)
    --or
    Delete t
    From t1 t
    left JOIN t2 m
    ON m.N1=t.N1 and m.N2=t.N2
    WHERE m.N1 is null and m.N2 is null
    --Or
    ;With mycte as
    select N1,N2 from T1
    Except
    select N1,N2 from T2
    Delete t
    From t1 t
    INNER JOIN mycte m
    ON m.N1=t.N1 and m.N2=t.N2

Maybe you are looking for