0

I have two tables with same number of columns :-Table A and Table B Every day I insert data from Table B to Table A. now the insert query is working

insert into table_a (select * from table_b);

But by this insert the same data which was inserted earlier that is also getting inserted. I only want those rows which are new or are changed from the old data. How can this be done ?

1
  • take a look at fast-refreshable materialized views. in case your table_a is read-only (no other operation than this insert-select are performed), this could be the easiest option Commented Jul 19, 2014 at 18:04

4 Answers 4

2

You can use minus:

insert into table_a
    select *
    from table_b
    minus
    select *
    from table_a;

This assumes that by "duplicate" you mean that all the columns are duplicated.

Sign up to request clarification or add additional context in comments.

1 Comment

In addition, if (by chance) you have a date modified column, select only where the date modified from table b > the max from table a.
0

If you have a timestamp field, you could use it to limit the records to those created after the last copy.

Another option is, assuming that you have an primary key (id column in my example) that you can use to know whether a record has already been copied, you can create a table c (with the same structure as a and b) and do the following:

insert into table c 
  select a.* from table a
  left join table b on (a.id=b.id)
  where b.id is null;

insert into table b select * from table c;

truncate table c;

You need to adjust this query in order to use the actual primary key.

Hope this helps!

Comments

0

If the tables have a primary or unique key, then you could leverage that in an anti-join:

insert into table_a
select *
from table_b b
where not exists (
  select null
  from table_a a
  where
    a.pk_field_1 = b.pk_field_1 and
    a.pk_field_2 = b.pk_field_2
)

Comments

0

You don't say what your key is. Assuming you have a key ID, that is you only want ID's that are not already in Table A. You can also use Merge-Statement for this:

MERGE INTO A USING B ON (A.ID = B.ID)
WHEN NOT MATCHED THEN INSERT (... columns of A) VALUES (... columns of B)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.