How to copy a row from a table to another table if the record does not exist in the new table in sql

I need to copy all the data from a table to another schema table. If the new table already has a row, I do not need to update or insert it. I need only new data from the old table that does not exist in the new table to copy to this new table.

So what will the sql query be, can anyone help me.

Thank you Muntasir Rahman Rafi

+4
source share
2 answers

try the following:

INSERT INTO TABLENAME2 (col1, Col2, col3) SELECT * FROM tablename1 A WHERE NOT EXISTS ( SELECT * FROM tablename2 B WHERE A.col1 = B.col1 ) 
+9
source

Try this option -

 INSERT INTO new_table(...) SELECT * FROM old_table AS o WHERE o.ID NOT IN ( SELECT n.ID FROM new_table AS n ) 

Or that -

 INSERT INTO new_table(...) SELECT o.* FROM old_table AS o LEFT JOIN new_table AS n ON n.ID = o.ID WHERE n.ID IS NULL 
+4
source

Source: https://habr.com/ru/post/1490423/


All Articles