Python MySQL – Insert record if not exists in table
Prerequisite: Connect MySQL Database to Python
In this article, we will try to insert records and check if it EXISTS or not. The EXISTS condition in SQL is used to check if the result of a correlated nested query is empty (contains no tuples) or not. It can be used to INSERT, SELECT, UPDATE, or DELETE statement.
The query we are using the python program is:
INSERT INTO table-name(col1, col2, col3) \
SELECT * FROM (SELECT val1, val2, val3) as temp \
WHERE NOT EXISTS \
(SELECT primary-key FROM table-name WHERE primary-key = inserted-record) LIMIT 1
Suppose we have a database called test and a table named in geeksfoegeeks. Below are the schema and data of the table:
Since each individual has a unique identification number, we will insert records and check the ID_NO of that person. If ID_NO is not already present in the table, the record will be inserted, else the record will be discarded. Let us understand using the below examples:
Example 1: When the record does not exist in the table.
In the above, output we could see that the record (‘Thomas’,’UK’,30,1892345670,’IND100′) was inserted into MySQL table.
Example 2: When record already Exists
Below are the schema and data of the table geeksdemo in database geek:
Now, we will try to insert a record that already exists.
We observe that record (5,’Thomas’,’m’,’information technology’) was not inserted into the table again. The following image is the output of MySQL database, after running the above python script.
We can see that 0 rows were affected. Therefore, no record was inserted as it already existed in the table with another record.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course