I wanted to build a generic function in Python to Insert a record into table A from table B if the record does not exists in table A else update with the data if the primary key is identified. I am not able to get the result with the below code:
def insert_update_record(table_A, table_B):
insert_query = "INSERT INTO {} SELECT * FROM {} WHERE NOT EXISTS (SELECT 1 FROM {} WHERE {}.id = {}.id)".format(table_A, table_B, table_A, table_B, table_A)
update_query = "UPDATE {} SET {} = {} FROM {} WHERE {}.id = {}.id".format(table_A, table_A, table_B, table_A, table_B, table_A)
cur.execute(insert_query)
cur.execute(update_query)
conn.commit()
First, I should say
SELECT 1in yourinsert_queryis not ok and you probably need to change it to something like this:But what you want to implement is a concept called
Upsertin database concepts and I do it for you usingINSERT ON CONFLICTstatement like below:Reference:
To learn more about this concept in Postgres or other databases you can tour the below links:
Psycopg2: how to insert and update on conflict using psycopg2 with python? [stackoverflow]
Insert, on duplicate update in PostgreSQL? [stackoverflow]
PostgreSQL Upsert Using INSERT ON CONFLICT statement [POSTGRESQL TUTORIAL]
How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL? [stackoverflow]
Idiomatic way to implement UPSERT in PostgreSQL [dba-stackexchange]