Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
Silva Web Designs - Blog

How to insert if something does not exist in MySQL database

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');
Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development and web site design. His expertise is WordPress & Magento as well as many other frameworks. Would you like to work with Nathan? Send him an email on [email protected]

It’s good to share

Join the discussion