0

Is there a way in db2 where I can replace the entire table with just selected rows from the same table ?

Something like REPLACE into tableName select * from tableName where col1='a';
(I can export the selected rows, delete the entire table and load/import again, but I want to avoid these steps and use a single query).

Original table
col1 col2
a 0 <-- replace all rows and replace with just col1 = 'a'
a 1 <-- col1='a'
b 2
c 3

Desired resultant table
col1 col2
a 0
a 1

Any help appreciated !
Thanks.

3
  • why can't you just DELETE FROM mytbl WHERE COL1 <>'a'?
    – Charles
    May 20, 2015 at 19:22
  • the table contains lots of columns, it would just make the query really long. Since there is a replace keyword, I wanted to know if there is a workaround to that delete method. May 20, 2015 at 19:55
  • I don''t understand. What does the number of columns have to do with anything? If you' talking about the number of comparisons in the WHERE clause, you'd have to do the same number regardless of rather your keeping the rows you want or deleting the rows you don't want. Added an answer with a code example..
    – Charles
    May 21, 2015 at 13:29

2 Answers 2

1

This is a duplicate of my answer to your duplicate question:

You can't do this in a single step. The locking required to truncate the table precludes you querying the table at the same time.

The best option you would have is to declare a global temporary table (DGTT) and insert the rows you want into it, truncate the source table, and then insert the rows from the DGTT back into the source table. Something like:

declare global temporary table t1 
   as (select * from schema.tableName where ...) 
   with no data
   on commit preserve rows
   not logged;

insert into session.t1 select * from schema.tableName;

truncate table schema.tableName immediate;

 insert into schema.tableName select * from session.t1;
0

I know of no way to do what you're asking in one step...

You'd have to select out to a temporary table then copy back.

But I don't understand why you'd need to do this in the first place. Lets assume there was a REPLACE TABLE command...

REPLACE TABLE mytbl WITH (
  SELECT * FROM mytbl
  WHERE col1 = 'a' AND <...>
)

Why not simply delete the inverse set of rows...

DELETE FROM mytbl
WHERE NOT (col1 = 'a' AND <...>)

Note the comparisons done in the WHERE clause are the exact same. You just wrap them in a NOT ( ) to delete the ones you don't want to keep.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.