Menu Close

How to insert if something does not exist in MySQL database

default

When we create a database table we try to make sure that on certain tables we only allow the user to insert a unique record. To achieve this, we assign a primary key to the table but sometimes duplicate records can be inserted as there may not be any validations in place.

The code below allows you to insert records only if it doesn’t already exist in the table:


INSERT INTO user (Name,username,password)
SELECT * FROM (SELECT 'Name', 'Address', 'Postcode') 
AS tmp WHERE NOT EXISTS 	
(SELECT Name,username,password 
FROM user WHERE Name = 'Name' and username = 'Address' and password = 'Postcode');
View Source
Posted in MySQL