Question: I created a table to hold the customer information, and I know that you can insert the information into the table with the INSERT statement, but how do you guarantee that you don't insert duplicate records?
Answer: You can prevent the insertion of duplicate records by using EXISTS conditional sentences.
Example one: inserting more than one record
Suppose you have a clients table with a primary key of client_id, you can use the following statement:
The code is as follows |
Copy Code |
INSERT into clients (client_id, Client_name, Client_type) SELECT supplier_id, Supplier_name, ' advertising ' From suppliers WHERE NOT EXISTS (SELECT * from clients where clients.client_id = suppliers.supplier_id);
|
Example one: inserting a single record
The code is as follows |
Copy Code |
INSERT into clients (client_id, Client_name, Client_type) SELECT 10345, ' IBM ', ' advertising ' From dual WHERE NOT EXISTS (SELECT * from clients where clients.client_id = 10345);
|
Using dual as a table name allows you to follow directly to the value of the field you want to insert after the SELECT statement, even if the values do not yet exist in the current table