Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres insert only new rows to the table

I have such a code,

  cursor_local.execute("""SELECT "Name", "Level_Capacity", "Source_NE", "Sink_NE" FROM "table1" WHERE "Name" LIKE '%WDM%' """)
  rows = cursor_local.fetchall()

  psycopg2.extras.execute_batch(cursor_local, 'INSERT INTO table2("Name", "Level_Capacity", "Source_NE", "Sink_NE") VALUES (%s, %s, %s, %s)', (*rows,) )
  connection_local.commit()

and I would like to insert only new records into the table2 from table1 (postgres db), only those that are not in table2. In table2 "Id" is automatically generated and is unique (others are not unique) , when inserting I would like to check if it exists "Name", "Source_NE", "Sink_NE".

like image 500
Kriss Avatar asked Jun 10 '26 16:06

Kriss


1 Answers

is "name" unique? maybe you can do an ON CONFLICT Name DO NOTHING

INSERT INTO table2
VALUES ,,,
ON CONFLICT 'Name' DO NOTHING;

else you could do a NOT IN (SELECT "Name" etc FROM table2) etc

INSERT INTO table2
VALUES (
    SELECT * FROM table1 WHERE ('Name' etc)
    NOT IN (SELECT 'Name', etc FROM table2)
    )
like image 122
mnzbono Avatar answered Jun 12 '26 06:06

mnzbono