Comparing two postgres tables and updating one with differences.

I have two tables in a postgres database
  Table 1
  Table 2
Table 2 contains all the newacctnumber/oldaccountnumber entrees that exist in table 1.  Some other steps are take and then the done is set to Y.

Table 1 is automatically generated each week, resulting in additional entreens being added.

What I need to do is update table 2 with new entrees that are in Table 1 but not already in Table 2.

This will be done thru an online page (administrators page) with php code.  I have one method but it seems slow to me.

      $query="Select * from table1";
      $db = "poscoid";
      $result = db_query($query, $db);
      while ($r=pg_fetch_array($result))
               $newacctnumber = $r["newacctnumber"];
               $oldacctnuber = $r["oldacctnumber"];
    $query="Insert into table2(newacctnumber, oldacctnumber) values($newacctnumber,$oldacctnumber) where $newacctnumber not in (select newacctnumber from table2 where done = 'N')";
      $db = "poscoid";
      $updateresult = db_query($query, $db);
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You could try something like (from mysql, but might also work for postgres). Maybe you need to move the result of select newacctnumber from table2 where done = 'N') first to a temp-table:

INSERT INTO table2(newacctnumber, oldacctnumber)  SELECT table1.newacctnumber, table1.oldacctnumber FROM table1 WHERE table1.newacctnumber  not in (select newacctnumber from table2 where done = 'N')

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MarkApplegateAuthor Commented:
Thanks for the brain jog hernst42.  I knew there was a way to avoid the php, just couldn't force it out of the grey matter.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.