1

I want to replace existing records in a table with records from a new table that have the same key.

In SQL, for example, I would just execute the following two statements:

DELETE O FROM OLD_TABLE T1
    WHERE EXISTS (SELECT * FROM NEW_TABLE T2
                  WHERE T1.KeyPart1 = T2.KeyPart1
                  AND   T1.KeyPart2 = T2.KeyPart2 )

INSERT OLD_TABLE 
     SELECT * FROM NEW_TABLE T2
     WHERE NOT EXISTS (SELECT * FROM OLD_TABLE T1
                        WHERE T1.KeyPart1 = T2.KeyPart1
                        AND   T1.KeyPart2 = T2.KeyPart2)

In Python, How would I do this using SQLAlchemy Core (NOT the ORM)?

OldTable.delete().????   
OldTable.insert(NewTable.select()) ????

I'm afraid I'm totally lost.

P.S. I'm doing this in SQLAlchemy CORE because (a) there's a log of records, and (b) I want SQLAlchemy to handle the database dialect dependence.

1 Answer 1

1

an "exists" is handled in the WHERE clause using exists(), and "INSERT .. FROM SELECT" is via from_select().

conn.execute(
   old_table.delete().where(exists().where(
              old_table.c.col == new_table.c.col
             ).where(
              old_table.c.col2 == new_table.c.col2).
              correlate(old_table)
   )
)

conn.execute(
      old_table.insert().from_select(['col', 'col2'], new_table.select().where(
      ~exists().where(old_table.c.col == new_table.c.col).correlate(new_table)
      )    
)
Sign up to request clarification or add additional context in comments.

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.