Search code examples
sqloraclesql-delete

Delete Records from table on the basis of inner join


I have two tables in oracle DB called collection and collection_h. I have to delete all the records from collection_h which has the same below fields in the collection table.

I have to delete all the records from collection_h table that comes out as a result of the below query:

select * from collection inner join collection_h on
collection.pos_protocol_id  = collection_h.pos_protocol_id and
collection.terminal_pos_number = collection_h.terminal_pos_number and
collection.cb_file_number = collection_h.cb_file_number and
collection.cb_block_number = collection_h.cb_block_number and
collection.is_stan_batch = collection_h.is_stan_batch and
collection.is_transaction_date = collection_h.is_transaction_date and
collection.is_stan_trans = collection_h.is_stan_trans;

Solution

  • Delete where exists

    delete
    from collection as c
    where exists (
      select 1
      from collection_h as h
      where h.pos_protocol_id  = c.pos_protocol_id
        and h.terminal_pos_number = c.terminal_pos_number 
        and h.cb_file_number = c.cb_file_number 
        and h.cb_block_number = c.cb_block_number 
        and h.is_stan_batch = c.is_stan_batch  
        and h.is_transaction_date = c.is_transaction_date
        and h.is_stan_trans = c.is_stan_trans
    );
    

    Simplified test on db<>fiddle here

    But if the columns can have NULL's in the matching rows

    delete
    from collection as c
    where exists (
      select 1
      from collection_h as h
      where decode(h.pos_protocol_id, c.pos_protocol_id, 0, 1) = 0
        and decode(h.terminal_pos_number, c.terminal_pos_number, 0, 1) = 0 
        and decode(h.cb_file_number, c.cb_file_number, 0, 1) = 0
        and decode(h.cb_block_number, c.cb_block_number, 0, 1) = 0
        and decode(h.is_stan_batch, c.is_stan_batch, 0, 1) = 0
        and decode(h.is_transaction_date, c.is_transaction_date, 0, 1) = 0
        and decode(h.is_stan_trans, c.is_stan_trans, 0, 1) = 0
    );